AWS Loves Next.js

How AWS provides seamless development and deployment experience for Next.js apps

Dilantha Prasanjith
Bits and Pieces

--

Today, when we develop modern web applications, we should use a suitable page rendering technique that makes sense to our application. You may use Server-Side Rendering(SSR), Static Site Generation (SSG), Client-side rendering, or a mix of these techniques.

Next.js is a fast and reliable way to build production-ready React web applications that supports all three rendering modes mentioned above.

The best thing about Next.js is that you can use a blend of SSR, SSG or Client-side rendering in the same application as per your use case.

Because of this flexibility, the major players in the IT industry have started embracing Next.js rapidly. Therefore public cloud providers like AWS and Azure began to providing more support and love to Next.js.

In this article, let’s discuss how AWS provides a seamless experience in developing and deploying Next.js applications.

What’s so special about Next.js?

As mentioned above, the ability to use one or more page rendering techniques in the same application is the main benefit of using Next.js. But, there are so many other cool features that Next.js support out of the box.

  • Automatic code splitting, minifying JS, and pre-fetch assets for faster page loads
  • File system based routing allows your application to scale up for thousands of pages without performance issues
  • Built-in CSS and Sass support and support for any CSS-in-JS library
  • API routes to build API endpoints with Serverless Functions
  • Built on top of webpack, which enables polyfills, ignoring dev only dependencies etc. You can also customize webpack configuration if required.

Because of these benefits and its popularity in the community, AWS has made Next.js a first-class citizen in their platform. Look at the recent announcement from AWS, which announces the out-of-the-box server-side rendering support for AWS Amplify.

Well, this welcoming atmosphere is not only limited to just AWS, but Azure and Netlify are also doing the same.

How to develop Next.js apps on AWS?

We can use AWS Amplify Framework to develop Next.js apps on AWS. Amplify Framework is the easiest way to get started with Web/Mobile application development on AWS. It provides four main components for developers.

  • Amplify CLI
  • Amplify Libraries
  • Amplify UI Components
  • Amplify Admin UI

Amplify CLI is used to provision resources at the AWS end and Amplify Libraries are used to communicate with those provisioned resources from different clients such as web browsers, android/ios mobile apps, etc.

Both Amplify CLI and Library have direct support for Next.js apps. Amplify CLI understands the structure of a Next.js app and add the configurations accordingly. Amplify JavaScript Library support unique methods to work with SSR context.

Have a look at the following steps to add Amplify support to your Next.js apps.

Step 01

Create a Next.js app

npx create-next-app next-amplified

Step 02

Initialize an amplify backend with the following command. You have to install Amplify CLI before prior running this command.

amplify init

Step 03

Install amplify libraries to communicate with the AWS backend and use UI components for React.

npm install aws-amplify @aws-amplify/ui-react

Step 04 (Optional)

Let’s imagine your Next.js app needs a GraphQL API at AWS as its backend. If so add it using the following CLI command.

amplify add api

Step 05

Configure amplify backend with your Next.js app. Open pages/index.js file and add the initial configuration.

import { Amplify, withSSRContext } from "aws-amplify";
import awsExports from "../src/aws-exports";
Amplify.configure({ ...awsExports, ssr: true });

Step 06

If we want to configure the Next.js app to communicate with the GraphQL API we can use getServerSideProps, getStaticProps, and getStaticPaths functions and use Amplify library methods that support SSR.

import { Amplify, API, withSSRContext } from "aws-amplify";
import awsExports from "../src/aws-exports";
Amplify.configure({ ...awsExports, ssr: true });export async function getStaticPaths() {
const SSR = withSSRContext();
const { data } = await SSR.API.graphql({ query: listPosts });
// Example of getting list of posts from GraphQL API
const paths = data.listPosts.items.map((post) => ({
params: { id: post.id },
}));
return {
fallback: true,
paths
};}
export async function getStaticProps({ params }) {
const SSR = withSSRContext();
// Example of getting one post
const { data } = await SSR.API.graphql({
query: getPost,
variables: {
id: params.id,
},
});
return {
props: {
post: data.getPost,
}
};}

How to deploy Next.js apps in AWS?

Now let’s look at the options available to deploy a Next.js application on the AWS platform.

Deploy as a static site on S3

This is the most basic, but not that feature-rich approach. You would generate a static HTML version of your web application and host it in an S3 bucket. And connect it with a CloudFront distribution. This will be very similar to any other CDN system.

In this, all you have to do is run next build && next export and it will generate the HTML version.

Deploy as a server-side rendered Node.js application

With this approach, what you can do is running an ec2 instance, which has NodeJS runtime. This is also not any specific setup. It will be similar to how you would run a Next.js application on any NodeJS server.

Deploy as a Serverless Next.js Component using Serverless Framework

Serverless Framework is a popular framework to develop serverless backend for major cloud providers including AWS. They have built a component to deploy Next.js apps to AWS fast with Zero configurations.

Have a look at the following diagram to understand what does this serverless component do behind the scenes.

Essentially it’s going to create the following services on AWS when deploying a Next.js app using the serverless framework.

  1. CloudFront distribution
  2. S3 bucket
  3. Lambda@Edge functions

The build assets and user assets (see the diagram) will be deployed to S3 and served via the CloudFront distribution. CloudFront is a CDN in AWS which operates at Edge Locations around the world closer to the users. It can cache the static assets and deliver them to the end-users quite fast.

If we look at the main AWS resources, there will be a Cloudfront distribution, a Lambda@edge, and an S3 bucket under the hood.

Lambda@Edge functions are serverless functions that operate at CloudFront edge locations. They are responsible for performing server-side rendering of the Next.js webpages closer to the user with minimum latency.

So here’s what happens.

  1. Server Side Rendered pages (SSR) will be rendered at the CloudFront level and will be sent back to the user immediately
  2. Static pages (SSG) be forwarded to s3 since these are generated at build time

How to use the Serverless Next.js Component?

Now that we understand the architecture, let’s see how to deploy a Next.js application using the Serverless Next.js Component.

The Serverless Next.js Component is built with three design principles in mind.

  1. Zero configuration by default
  2. Feature parity with Next.js
  3. Fast deployments

Zero configuration by default

You can use the component right away without worrying about any additional configurations. It’s only about adding below to your Serverless.yml file.

# serverless.yml
myApp:
component: serverless-next.js

And then run the following command.

$ npx serverless

If you need to remove your serverless application, run the following command.

$ npx serverless remove

If you need to include additional configurations you can also do that by updating the serverless component. (E.g. Adding a custom domain to your Next.js app)

Feature parity with Next.js

This design principle states that the features available in Next.js should be available with the serverless component.

For a list of features available, you can check the docs.

Fast deployments (20X faster)

Serverless components are enhanced versions of the Serverless plugins. Serverless plugins create and run a CloudFormation stack at deployment. However, serverless components do not create a CloudFormation stack but it use a different approach. This makes deployment 20X faster than traditional deployment.

Read more about serverless components here.

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Conclusion

Next.js is a fast and straightforward approach to build modern React applications with features like SSR and SSG. Most of the big players in the IT industry have started using Next.js to develop their highly scalable applications.

Public cloud providers like AWS have also started giving support for Next.js with love. With AWS Amplify and Serverless Framework direct support, we now have a smooth process to develop and deploy production-ready Next.js apps on AWS.

Thank you for reading. And don’t forget to tell us what you think in the comment section 🤔

Learn More

--

--