How to Deploy Next.js to AWS: Step-by-Step Guide
To deploy a
Next.js app to AWS, you can use AWS Amplify for a simple, managed hosting solution or AWS Elastic Beanstalk for more control. Both methods involve building your app locally, then uploading or connecting your code repository to AWS services for deployment.Syntax
Deploying Next.js to AWS typically involves these steps:
- Build your Next.js app: Run
npm run buildto prepare production files. - Choose AWS service: Use
AWS Amplifyfor easy hosting orAWS Elastic Beanstalkfor full server control. - Deploy: Connect your code repository or upload build files to AWS and configure environment settings.
bash
npm run build # For AWS Amplify CLI deployment amplify init amplify add hosting amplify publish # For Elastic Beanstalk deployment zip -r app.zip . eb init eb create eb deploy
Example
This example shows how to deploy a Next.js app to AWS Amplify using the Amplify CLI.
First, build your app locally, then initialize Amplify, add hosting, and publish.
bash
npm run build npx @aws-amplify/cli@latest init npx @aws-amplify/cli@latest add hosting npx @aws-amplify/cli@latest publish
Output
ā Initialized Amplify project
ā Added hosting with Amazon CloudFront and S3
ā Published app to AWS Amplify hosting
Hosting URL: https://yourapp.amplifyapp.com
Common Pitfalls
Common mistakes when deploying Next.js to AWS include:
- Not building the app before deployment, causing missing production files.
- Using server-side features without configuring AWS Lambda or server support.
- Ignoring environment variables setup in AWS, leading to runtime errors.
- Uploading source code instead of the built output for static hosting.
Always build your app and configure environment variables properly.
bash
Wrong (deploying without build): # Uploading source files directly aws s3 cp ./ . --recursive Right (build before deploy): npm run build aws s3 cp ./out/ . --recursive
Quick Reference
| Step | AWS Amplify | AWS Elastic Beanstalk |
|---|---|---|
| Build app | npm run build | npm run build |
| Initialize | amplify init | eb init |
| Add hosting | amplify add hosting | Configure Docker or Node.js environment |
| Deploy | amplify publish | eb create && eb deploy |
| Environment vars | Set in Amplify Console | Set in Elastic Beanstalk config |
Key Takeaways
Always run npm run build before deploying your Next.js app to AWS.
Use AWS Amplify for simple hosting or Elastic Beanstalk for more control.
Configure environment variables in AWS to avoid runtime errors.
Do not upload source code directly when using static hosting like Amplify.
Test your deployed app URL to confirm successful deployment.