View a markdown version of this page

Connect an AWS Lambda function - AWS Amplify

Connect an AWS Lambda function

An AWS Lambda function calls the Amplify backend of your AWS Amplify app with the same backend client SDK as your app. It calls the backend with full access, or as the signed-in user when your app sends it the user’s token. Create the function in the AWS account and Region of your app. To create a function, see Create your first Lambda function in the AWS Lambda Developer Guide.

Add the function to your repository

Keep each function in its own folder under functions/, with its own package.json, next to your app:

my-app/ ├── amplify.jsonc ├── app/ ├── migrations/ └── functions/ ├── template.yaml └── notes-report/ ├── index.mjs └── package.json

Run the following command in the function’s folder to install the SDK:

npm install @aws-amplifygen3/backend-client-js @aws-sdk/credential-providers

The function reads the backend URL and the publishable key from the environment variables AMPLIFY_BACKEND_URL and AMPLIFY_BACKEND_PUBLISHABLE_KEY. You set both when you deploy it. For more information, see Deploy functions with your app.

Give the function access to a backend branch

Give the function’s execution role permission for amplifygen3:Connect on one backend branch, in the same AWS account and Region as the function. The branch ARN has the following form:

arn:aws:amplifygen3:<Region>:<account-id>:app/<app>/environment/<env>/branch/<branch>

Run the following command to get an environment’s backend URL, publishable key and branch ARN:

aws amplifygen3 backend info --env production --output json

The output has BackendUrl, PublishableKey and BranchArn. BranchArn goes in the role’s permission, and BackendUrl and PublishableKey become the function’s environment variables. In an AWS Serverless Application Model (AWS SAM) template, add the permission under the function’s Policies:

Policies: - Statement: - Effect: Allow Action: amplifygen3:Connect Resource: arn:aws:amplifygen3:us-east-1:111122223333:app/my-app/environment/production/branch/production

Call the backend with full access

To read or change every row, create the client with awsCredentialsProvider and no publishable key. The SDK signs each request with the credentials of the function’s execution role, and the request runs as service_role. For the roles, see API keys and roles.

// functions/notes-report/index.mjs import { createClient } from '@aws-amplifygen3/backend-client-js' import { fromNodeProviderChain } from '@aws-sdk/credential-providers' const admin = createClient(process.env.AMPLIFY_BACKEND_URL, { awsCredentialsProvider: fromNodeProviderChain(), }) const countNotes = async () => { const { count, error } = await admin.from('notes').select('*', { count: 'exact', head: true }) if (error) throw new Error(`${error.code}: ${error.message}`) return { totalNotes: count } }

Act as the signed-in user

To return only the rows that a user may see, have your app send the user’s token, and create the client with it. The row-level security (RLS) policies that you configured apply to each request. For more information, see Secure your data.

In your app, call backend.auth.token() before each call to the function, and send the token in the Authorization header. Each call to backend.auth.token() returns a new token.

const { data, error } = await backend.auth.token() if (error || !data) throw error ?? new Error('Sign in first') const res = await fetch(process.env.NEXT_PUBLIC_NOTES_REPORT_URL!, { headers: { Authorization: `Bearer ${data.token}` }, })

In the function, create the client with the backend URL, the publishable key and webTokenProvider, a function that returns the user’s token. Answer 401 when the token is missing or the backend returns invalid_credential:

const asUserHandler = async (event) => { const header = event.headers?.authorization ?? '' const token = header.startsWith('Bearer ') ? header.slice(7) : '' if (!token) return { statusCode: 401, body: JSON.stringify({ error: 'Sign in first' }) } const asUser = createClient(process.env.AMPLIFY_BACKEND_URL, process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY, { webTokenProvider: () => token, }) const { data, error } = await asUser.from('notes').select('id, body') if (error?.code === 'invalid_credential') return { statusCode: 401, body: JSON.stringify({ error: error.message }) } if (error) return { statusCode: 500, body: JSON.stringify({ error: error.message }) } return { statusCode: 200, body: JSON.stringify({ notes: data }) } }

Add a function URL

To call the function from your app over HTTPS, give it a function URL with CORS for your app’s origin. In the AWS SAM template, add FunctionUrlConfig to the function:

FunctionUrlConfig: AuthType: NONE Cors: AllowOrigins: [https://www.example.com] AllowHeaders: [authorization, content-type] AllowMethods: [GET]

With AuthType: NONE, anyone can call the URL. The URL is safe when the function acts as the signed-in user for every URL request: it answers 401 to a request without a valid token, and each query that it makes with a user’s token runs under the RLS policies that you configured. Use the full-access client only for events that aren’t URL requests, such as a schedule. For more information, see Lambda function URLs in the AWS Lambda Developer Guide.

A request to the function URL has requestContext.http in its event. The following handler acts as the user for those requests, and uses full access for the rest:

export const handler = async (event) => { if (event.requestContext?.http) return asUserHandler(event) // a function URL request return countNotes() // a schedule or a direct invoke }

Give your app the function’s URL

Run the following command to give each environment of your app the URL of its own function:

aws amplifygen3 var set NEXT_PUBLIC_NOTES_REPORT_URL https://abcdefexample.lambda-url.us-east-1.on.aws/ --env preview

Your app reads the value from process.env after the environment’s next deployment. Browser code gets a variable only through your framework, so the name has the NEXT_PUBLIC_ prefix that Next.js builds into browser code. With another framework, use its prefix, such as VITE_. The function URL isn’t a secret. For more information, see Environment variables.

Call the function from server code

To call the function from server code in your app, forward the Authorization header that your browser code sent:

// app/api/report/route.ts export async function GET(request: Request) { const authorization = request.headers.get('authorization') const res = await fetch(process.env.NEXT_PUBLIC_NOTES_REPORT_URL!, { headers: authorization ? { authorization } : {}, }) return Response.json(await res.json(), { status: res.status }) }

The function answers with the notes of the user whose token you forwarded.

Test the function locally

While the local backend runs, run the following command in the function’s folder to call the handler against it. The command needs no AWS credentials.

AMPLIFY_BACKEND_URL=http://localhost:3001 AMPLIFY_BACKEND_PUBLISHABLE_KEY=hpk_v1.local \ node -e "import('./index.mjs').then(async (m) => console.log(await m.handler({})))"

For more information, see Develop locally.

Errors

Error When What to do

FORBIDDEN (403), with the message Forbidden (HTTP 403). Request ID: <id>.

The execution role has no amplifygen3:Connect permission on the branch that the function calls

Grant amplifygen3:Connect on that branch’s ARN, from backend info for the same environment

invalid_credential

The token that the function sent isn’t a valid JWT, or the user’s session has ended

Answer 401, and have your app get a new token with backend.auth.token()

Your function’s 401

The request to the function URL had no Authorization header

Send Authorization: Bearer <token> from your app