Skip to content

Amplify deploy fails when using function resolver with env by TypeScript error #1374

@mm-k-takashima

Description

@mm-k-takashima

Environment information

System:
  OS: Windows 11 10.0.22631
  CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
  Memory: 4.69 GB / 15.79 GB
Binaries:
  Node: 20.12.0 - ~\AppData\Local\Volta\tools\image\node\20.12.0\node.EXE
  Yarn: undefined - undefined
  npm: 10.5.0 - ~\AppData\Local\Volta\tools\image\npm\10.5.0\bin\npm.CMD
  pnpm: undefined - undefined
NPM Packages:
  @aws-amplify/backend: 0.13.2
  @aws-amplify/backend-cli: 0.13.0
  aws-amplify: 6.0.30
  aws-cdk: Not Found
  aws-cdk-lib: 2.138.0
  typescript: 5.4.5
AWS environment variables:
  AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1
  AWS_SDK_LOAD_CONFIG = 1
  AWS_STS_REGIONAL_ENDPOINTS = regional
No CDK environment variables

Description

Code

Structure
amplify
├───data
│       └───resource.ts
└───functions
         └───function-with-env
                      ├───handler.ts
                      └───resource.ts
Implementations
  • amplify/functions/function-with-env/handler.ts
// ...

// Ref. https://docs.amplify.aws/gen2/build-a-backend/functions/#accessing-environment-variables 
/* @ts-noncheck directive for first 'amplify sandbox' run to avoid non-existence */
import { env } from '$amplify/env/function-with-env';

// ...
type FunctionWithEnvHandler = Schema['<query>']['functionHandler'];

export const handler: FunctionWithEnvHandler = async () => {
  const apiHost = env['API_HOST'];
  const apiKey = env['API_KEY'];

  // ... list items from outside service and resolve types ...
  
  return customTypeArray; 
}
  • amplify/functions/function-with-env/resource.ts
import { defineFunction, secret } from '@aws-amplify/backend';

const apiHost = process.env.API_HOST as string;
const apiKey = secret('API_KEY');

const environment = {
  API_HOST: apiHost,
  API_KEY: apiKey,
};

export const functionWithEnv= defineFunction({
  environment,
  timeoutSeconds: 10,
});
  • amplify/data/resource.ts
import { functionWithEnv } from '../functions/function-with-env/resource';
// ...

const schemaopt = {
  <custom-type>: a
    .customType({
      // typedef
    }),
  <query>: a
    .query()
    .returns(a.ref('<custom-type>').array())
    .handler([a.handler.function(functionWithEnv)])
    .authorization((auth) => [auth.guest(), auth.authenticated()]),
};
const schemaImpl = a.schema(schemaopt);
export type Schema = ClientSchema<typeof schemaImpl>;

export const data = defineData({
  schema: schemaImpl,
  authorizationModes: {
    defaultAuthorizationMode: 'userPool',
  },
});
// ...
Others
  • .amplify/generated/env/function-with-env.ts (git ignored)
// This file is auto-generated by Amplify. Edits will be overwritten.
export const env = process.env as LambdaProvidedEnvVars & AmplifyBackendEnvVars;

/** Lambda runtime environment variables, see https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime */
type LambdaProvidedEnvVars = {
  // ... auto generated settings ...
};

/** Amplify backend environment variables available at runtime, this includes environment variables defined in `defineFunction` and by cross resource mechanisms */
type AmplifyBackendEnvVars = {
  API_HOST: string;
  API_KEY: string;
};
  • amplify/tsconfig.json
{
  "compilerOptions": {
    "target": "es2022",
    "module": "es2022",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "paths": {
      "$amplify/*": ["../.amplify/generated/*"]
    }
  }
}

Error detail

Sandbox deploy is succeeded. But deploy on Amplify CI/CD is failed.

Deploy log
2024-04-24T10:07:52.788Z [INFO]: # Executing command: npx amplify pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID
2024-04-24T10:07:59.702Z [INFO]:
2024-04-24T10:08:05.537Z [INFO]: amplify/functions/<function-with-env>/handler.ts(4,21): error TS2307: Cannot find module '$amplify/env/<function-with-env>' or its corresponding type declarations.
2024-04-24T10:08:05.573Z [INFO]:
2024-04-24T10:08:05.573Z [WARNING]: amplify pipeline-deploy
Command to deploy backends in a custom CI/CD pipeline. This command is not intended to be used locally.

[...]

2024-04-24T10:08:05.574Z [INFO]: SyntaxError: TypeScript validation check failed.
Resolution: Fix the syntax and type errors in your backend definition.
Cause:
2024-04-24T10:08:05.634Z [ERROR]: !!! Build failed
2024-04-24T10:08:05.634Z [INFO]: Please read more about Amplify Hosting's support for SSR frameworks to find if your build failure is related to an unsupported feature: https://docs.aws.amazon.com/amplify/latest/userguide/amplify-ssr-framework-support.html. You may also find this troubleshooting guide useful: https://docs.aws.amazon.com/amplify/latest/userguide/troubleshooting-ssr-deployment.html
2024-04-24T10:08:05.634Z [ERROR]: !!! Error: Command failed with exit code 1

Expected

I want to meet these usecases.

  • Success 'npx amplify sandbox' (generated env is existing)
  • Success 'npx amplify sandbox' (generated env is not existing / first execution)
  • Success Amplify CI/CD

What method should I take?(How to avoid TS check, wait for fix, or else ...)

Metadata

Metadata

Assignees

Labels

documentationImprovements or additions to documentationfunctionIssue pertaining to Amplify Function

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions