AWS Amplify is a great tool which allows you to hit the ground running with a wide variety of frameworks and languages. Amplify gives you an easy way to not just host your application, but add in databases, authentication, lambda functions, API’s and more! However, when accessing SES and other AWS services from your API routes in NextJS, you have to be aware of a current issue. For context, I stumbled across this issue when trying to send an email via the SES SDK in an API route.
The Problem With Adding AWS SDKs
As of writing this post, there is an issue around accessing AWS service SDKs from API routes in NextJS. In short, the issue is that the environment variables needed for any AWS SDK (usually AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
) are not available to NextJS by default. This behaviour is similar to the way NextJS has to access Amplify AWS variables which is described here: https://docs.aws.amazon.com/amplify/latest/userguide/ssr-environment-variables.html.
In addition to the above, you cannot name anything in your environment variables in Amplify AWS_
as this is a reserved word.
The Solution?
So similarly to the workaround to get Amplify environment variables into your NextJS application, we need to add the credentials into Amplify’s environment variables list first, then into our NextJS application.
Step 1
Let’s go ahead and add in our AWS IAM credentials into our Amplify environment variables. You need to keep in mind that you cannot call them AWS_
. In my example, I’ve called them NOT_AWS_
.
Step 2
Now we have our environment variables in Amplify, we need to expose these variables to our NextJS application. We can do this in the Build settings
of Amplify. We also need to convert the variables to AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
to save us lines of code having to setup a configuration for the AWS SDKs. Let’s add the following line in the commands
section of the preBuild phase under - npm ci
. You can customise .env
to the file of your choosing.
- env | grep -e NOT_AWS_ | sed "s/NOT_AWS_/AWS_/" >> .env
The above line will display all of our environment variables, grab the ones that begin with NOT_AWS_
then run that through sed
which will change NOT_AWS_
to AWS_
. Then we will store that in a .env file.
Step 3
Now all you need to do is re-build your application. You should then be good to go and able to use the SDKs natively in your NextJS API routes.
const ses = new SES({ region: 'eu-west-2' })
So when will this just work?
If you’re interested, this isn’t the behaviour AWS wanted. They have a Github issue currently open to try and resolve this. You can check this out here: https://github.com/aws-amplify/amplify-hosting/issues/3205.
Do you need help with your development project?
If you need help with your development project, please feel free to drop me an email here.