How can I use AWS SDK Environment Variables on Vercel?

Vercel allows the use of specific environment variables that can be used for your deployments. These can be used to configure the AWS credentials used by your Serverless Function as well as the region.

Configuring credentials

To get started, add the following environment variables to your Vercel project:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN

The values for the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables are produced by AWS IAM when creating new access keys for an IAM User.

The AWS_SESSION_TOKEN environment variable is often used to provide a short-lived, temporary set of credentials and is not normally useful to set for static credentials. It may be useful for testing changes on preview or development branches.

Configuring region

The AWS region corresponding to the Vercel region in which a Serverless Function is deployed is preset in the environment of the Serverless Functions. For example, a Serverless Function deployed in the Vercel region sfo1 already has the AWS_REGION environment variable set to us-west-1. See supported regions for the Edge Network for more information.

The AWS region can be overridden by setting one of two environment variables:

  • AWS_REGION (preferred)
  • AWS_DEFAULT_REGION

The use of AWS_DEFAULT_REGION is not normally required for the AWS SDK, but is supported for completeness.

Using the configured variables in code

By using these specially named environment variables, manual configuration of the AWS SDK can be avoided. For example, to use these variables to authenticate an S3 client from the AWS SDK, use the following code:

pages/api/uploadToS3.js
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
// The credentials are read from the environment automatically
const s3Client = new S3Client({});
const uploadCommand = new PutObjectCommand({
Bucket: process.env.S3_BUCKET_NAME,
Key: 'file-name',
Body: 'file-body',
});

This works equally well with all AWS services supported by the SDK. For further examples, see AWS S3 Image Upload and AWS DynamoDB with Next.js API Routes.

Use of custom runtimes

All the runtimes supported by Vercel can use the environment variables described above. The use of custom runtimes may result in use of these variables causing a build-time error.

Custom runtimes that set the value of supportsWrapper to true in the Serverless Function config can make use of the AWS credential environment variables. See the Build API documentation for more details. Other runtimes must use alternative environment variable names and set up the AWS client manually.

Couldn't find the guide you need?