Back to articles

Serverless React with Next.js & AWS Amplify: A Hands-On Guide

AuthorMajd Muhtaseb05/23/202510 minutes
Serverless React with Next.js & AWS Amplify: A Hands-On Guide

Introduction

This guide walks you through creating and deploying a serverless React application using Next.js and AWS Amplify. Next.js provides the framework for building performant React applications, while AWS Amplify simplifies deployment and backend services.

Prerequisites

  • Node.js and npm installed
  • AWS account

Step 1: Create a Next.js Application

npx create-next-app my-serverless-app
cd my-serverless-app

Step 2: Initialize Amplify

npm install -g @aws-amplify/cli
amplify configure # Follow the prompts to configure your AWS account
amplify init

Choose the following settings:

  • Project name: my-serverless-app
  • Environment name: dev
  • Choose your default editor: (your preference)
  • App type: javascript
  • Framework: react
  • Source Directory Path: .
  • Distribution Directory Path: .next
  • Build Command: npm run-script build
  • Start Command: npm run-script start
  • Do you want to modify the AWS backend? N

Step 3: Add Amplify Hosting

amplify add hosting

Choose the following settings:

  • Select the environment setup: DEV (S3 only with HTTP) or PROD (CloudFront CDN with S3 origin) - Choose DEV for simple projects, PROD for best performance.
  • hosting bucket name: (Choose a unique name)
  • index document for your app: index.html
  • error document for your app: 404.html

Step 4: Deploy

amplify publish

This command builds your Next.js application and deploys it to AWS Amplify. Amplify will provide you with a URL to access your live application.

Step 5: Add API (Optional)

If you need an API, you can add an AWS Lambda function using Amplify.

amplify add api

Follow the prompts to configure your API. For example, you can create a REST API with a Lambda function that returns a simple JSON response.

// Example Lambda function (./amplify/backend/function/<your_function_name>/src/index.js)
exports.handler = async (event) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

Then, update your Next.js application to call the API. You'll need the aws-amplify package.

npm install aws-amplify @aws-amplify/ui-react
// Example Next.js component
import { API } from 'aws-amplify';
import { useEffect, useState } from 'react';

function MyComponent() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    async function fetchData() {
      const data = await API.get('<your_api_name>', '/items'); // Replace '/items' with your API path
      setMessage(data);
    }
    fetchData();
  }, []);

  return (
    <div>
      <p>Message from API: {JSON.stringify(message)}</p>
    </div>
  );
}

export default MyComponent;

Remember to configure Amplify in your _app.js file:

// _app.js
import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';
import '@aws-amplify/ui-react/styles.css'; //Optional styling

Amplify.configure(awsconfig);

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Then you need to add the auto generated aws-exports.js file to the project root

amplify push

Conclusion

This guide provided a basic overview of deploying a serverless React application with Next.js and AWS Amplify. Amplify simplifies the deployment process, allowing you to focus on building your application's features. Remember to explore Amplify's documentation for more advanced features and customizations.