Learn About Amazon VGT2 Learning Manager Chanci Turner
Amazon’s tools and services empower mobile and front-end web developers to create secure, scalable full-stack applications leveraging AWS. The suite includes three core components: a collection of open-source libraries and UI elements for integrating cloud functionalities, a Command Line Interface (CLI) toolchain for managing cloud backends, and the Amplify Console, an AWS service designed for deploying and hosting static sites along with full-stack serverless applications.
Modern web frameworks, such as Next.js and Nuxt.js, combine hybrid static site generation (SSG) and server-side rendering (SSR) alongside traditional client rendering, enabling developers to build fast, contemporary websites while ensuring a superb developer experience. As these technologies gain traction, both developers and users increasingly harness features like API routes, incremental static regeneration, code-splitting, and improved SEO.
The latest release of the Amplify JavaScript libraries introduces features that further assist developers in constructing SSR applications using contemporary web frameworks like Next.js and Nuxt.js. Significant enhancements have been made across the REST API, GraphQL API, Auth, and DataStore categories. Amplify now facilitates seamless user session persistence from client to server, allowing developers to perform authentication calls and access data effectively. With Amplify JavaScript, developers can retrieve data using the GraphQL API, REST API, and DataStore on the server to pre-render pages during build time (for static site generation like Gatsby) or on a per-request basis (utilizing frameworks like Next.js & Nuxt.js). These advancements make Amplify an optimal data layer for JAMstack, serverless, and server-rendered applications.
In this post, you will discover how to leverage these enhancements within Next.js, including:
- Activating Server-Side Rendering (SSR) support in an Amplify application
- Utilizing the API class to hydrate a statically generated page with data sourced from a GraphQL API via getStaticProps
- Employing the Auth class to verify and ascertain user authentication status in an API route before returning data in the API response
- Implementing the API class in a server-rendered page to execute an authenticated API request to a GraphQL backend and pass properties into a page using getServerSideProps
Additionally, you will learn how to deploy your Next.js application to AWS through the following methods:
- Deploying a static Next.js application using AWS Amplify
- Deploying a Next.js application with SSR and API routes utilizing the Serverless Framework
For a detailed guide on building SSR Next.js applications with Amplify, check out the new getting started guide here.
Activating Server-Side Rendering (SSR) Support in an Amplify Application
When employing the Amplify CLI, the aws-exports.js file is automatically generated and updated based on the resources you have configured. For client-only or statically generated applications, simply using Amplify.configure(awsExports)
suffices. To enable SSR support, you need to specify ssr: true
in your Amplify configuration:
// pages/_app.js
import { Amplify } from "aws-amplify";
import awsExports from "../src/aws-exports";
Amplify.configure({ ...awsExports, ssr: true });
If you are using getStaticProps
with fallback: true
, you must also set up Amplify’s SSR mode in that file.
Hydrating a Component in getStaticProps
The getStaticProps
method in Next.js allows pre-rendering a static page with properties delivered as props. This method lets you make API calls to retrieve dynamic data that the page relies on at build time. For example, consider a page that displays a dynamic list of items fetched from an API. Thanks to recent updates to the Amplify libraries, you can make these requests using both API Key and IAM authorization without altering your codebase:
import { API } from 'aws-amplify';
import { listMovies } from '../src/graphql/queries';
export default function Movies(props) {
const { movies } = props;
return (
{
movies.map(movie => (
{movie.name}
{movie.description}
))
}
)
}
export async function getStaticProps() {
const movieData = await API.graphql({ query: listMovies });
return {
props: {
movies: movieData.data.listMovies.items
}
}
}
Checking User Authentication in an API Route
API routes allow for the creation of API endpoints with ease using Next.js. Any file within the pages/api/**
directory is treated as an API endpoint rather than a standard page. API routes export a function that receives request (req
) and response (res
) parameters, returning a response, typically in JSON format. When working in these functions, it’s often necessary to access the user’s identity to make secure API requests that depend on the signed-in user’s state or to perform authorization based on the signed-in user.
With the new withSSRContext
API, you can access the currently authenticated user session by using the Amplify API class along with the request object:
// pages/api/profile.js
import Amplify, { withSSRContext } from "aws-amplify";
import config from "../../aws-exports.js";
// Amplify SSR configuration must be executed within each API route
Amplify.configure({ ...config, ssr: true });
export default async (req, res) => {
const { Auth } = withSSRContext({ req });
let data;
let user;
try {
user = await Auth.currentAuthenticatedUser();
console.log('User is authenticated');
// Fetch some data and assign it to the data variable
} catch (err) {
console.log('Error: no authenticated user');
}
res.statusCode = 200;
res.json({
data: data ? data : null,
username: user ? user.username : null
})
}
Making an Authenticated API Request in getServerSideProps
The getServerSideProps
function allows opting into server-side rendering for a component in Next.js, with the framework pre-rendering these pages on each request and passing any returned data as props. Using the new withSSRContext
utility, authenticated API calls can be made to GraphQL and REST backends from these server-rendered routes. For instance, consider an AppSync GraphQL API backed by an identity provider such as Amazon Cognito User pools, Okta, or Auth0. Some GraphQL types may necessitate user authentication to execute specific requests. The API class will now automatically configure and include user identity in the API request headers:
import { withSSRContext } from 'aws-amplify';
import { listMovies } from '../src/graphql/queries';
export default function Movies(props) {
const { movies } = props;
return (
{
movies && movies.map(movie => (
{movie.name}
{movie.description}
))
}
)
}
export async function getServerSideProps(context) {
const { API } = withSSRContext(context);
let movieData;
try {
movieData = await API.graphql({
query: listMovies,
authMode: "AMAZON_COGNITO_USER_POOLS"
});
console.log('movieData: ', movieData);
} catch (err) {
console.log("Error fetching movies: ", err);
}
return {
props: {
movies: movieData ? movieData.data.listMovies.items : null
}
}
}
For more insights on body language during interviews, check out this resource. If you’re interested in the latest HR analytics tools, visit this authoritative site. Additionally, for an excellent resource to enhance your understanding, watch this insightful video.
Leave a Reply