A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.amplify.aws/gen1/react/build-a-backend/server-side-rendering/nextjs/ below:

Website Navigation


Use Amplify categories APIs from Next.js - React

Use Amplify categories APIs from Next.js

This guide walks through how to use Amplify Auth, GraphQL API, REST API, and Storage category APIs from Next.js server-side runtimes.

Note: Amplify JS v6 supports Next.js with the version range: >=13.5.0 <16.0.0. Ensure you have the correct version to integrate with Amplify.

Before you begin, you will need:

Configure Amplify in Next.js

You will need to create a runWithAmplifyServerContext function to use Amplify APIs on the server-side of your Next.js app.

You can create an amplifyServerUtils.ts file under a utils folder in your codebase. In this file, you will import the Amplify configuration object from the amplifyconfiguration.json file that is generated by the Amplify CLI, and use the createServerRunner function to create the `runWithAmplifyServerContext function.

For example, the utils/amplifyServerUtils.ts file may contain the following content:

You can use the exported runWithAmplifyServerContext function to call Amplify APIs with in isolated request contexts. Usage examples see here.

Tip: You only need to call the createServerRunner function once and reuse the runWithAmplifyServerContext function throughout.

Tip: You only need do this step if you are using Amplify APIs on the client side of your Next.js app, for example, calling Amplify Auth signIn API to sign in a user, or use GraphQL subscriptions on the client side.

When you use the Amplify library on the client-side of your Next.js app, you will need to configure Amplify by calling Amplify.configure as you would to use Amplify in a single-page application.

Note: To use the Amplify library on the client side in a Next.js app, you will need to set ssr to true when calling Amplify.configure. This instructs the Amplify library to store tokens in the cookie store of a browser. Cookies will be sent along with requests to your Next.js server for authentication.

Make sure you call Amplify.configure as early as possible in your application’s life-cycle. A missing configuration or NoCredentials error is thrown if Amplify.configure has not been called before other Amplify JavaScript APIs. Review the Library Not Configured Troubleshooting guide for possible causes of this issue.

To avoid repetitive calls to Amplify.configure, you can call it once in a top-level client-side rendered layout component.

Learn more

Configure Amplify in a Next.js App Router application

If you're using the Next.js App Router, you can create a client component to configure Amplify and import it into your root layout.

ConfigureAmplifyClientSide.tsx:

layout.tsx:

Authentication with Next.js server-side runtime (Experimental) Perform authentication on the server side and enable HttpOnly cookies

Warning: This feature is experimental and may change in future releases.

Once you enable the server-side sign-in feature, auth tokens are stored in HttpOnly cookies and you may not change the HttpOnly attribute. Since these cookies are inaccessible from client-side scripts, you won’t be able to use any Amplify JS APIs on the client side. Therefore, you don’t need to configure Amplify on the client side. You can keep using these Amplify JS server-side APIs on the server side.

Additional setup is required to enable server-side authentication flows in your Next.js app.

Step 1 - Specify the origin of your app in environment variables

Add the following environment variable to your Next.js app. For example in a .env file:

Ensure this environment variable is accessible in your Next.js app's server runtime.

Note: Token cookies are transmitted via server-side authentication flows. In production environments, it is recommended to use HTTPS as the origin for enhanced security.

Step 2 - Export the createAuthRouteHandlers function

The createAuthRouteHandlers function is created by the createServerRunner function call when you configure Amplify for server-side usage. You can export this function from your amplifyServerUtils.ts file. You can also configure cookie attributes with the runtimeOptions parameter.

Step 3 - Set up the Auth API routes

Create an API route using the createAuthRouteHandlers function. For example:

With the above example, Amplify generates the following API routes:

To customize the language of the Amazon Cognito Managed Login pages, you can add the lang query parameter to the /api/auth/sign-in and /api/auth/sign-up routes. For example, /api/auth/sign-in?lang=fr. Refer to the Managed login localization documentation for more information on the supported languages.

Note: A signing-out call involves multiple steps, including signing out from Amazon Cognito Managed Login, revoking tokens, and removing cookies. If the user closes the browser during the process, the following may occur:

  1. auth token have not been revoked - user remains signed in
  2. auth token have been revoked but cookies have not been removed - cookies will be removed when the user visits the app again
Step 4 - Provide the redirect URLs to the Auth Resource in Amplify

You can run amplify add auth or amplify update auth to provide the callback API routes as the redirect URLs. See Configure the Auth category for more details. With the above example, you can provide the following redirect URLs:

This enables Amazon Cognito Hosted UI to support the server-side authentication flows. You may upgrade to the latest Amazon Cognito Managed Login Branding to customize the sign-in and sign-up pages. See Amazon Cognito user pool managed login for more information.

Step 5 - Use Anchor link for initiating server-side authentication flows

Use HTML anchor links to navigate users to the sign-in and sign-up routes. For example:

When an end user clicks on the buttons above, a corresponding server-side authentication flow will be initiated.

Validate user session with the Next.js Middleware

You can use the fetchAuthSession API to check the auth sessions that are attached to the incoming requests in the middleware of your Next.js app to protect your routes. For example:

In this example, if the incoming request is not associated with a valid user session the request will be redirected to the /sign-in route.

Note: When calling fetchAuthSession with a response context, it will send the refreshed tokens (if any) back to the client via the Set-Cookie header in the response.

Calling Amplify category APIs on the server side

For the Auth, REST APIs, and Storage categories to use Amplify APIs on the server in your Next.js app, you will need to:

  1. Import the API from the /server sub path.
  2. Use the runWithAmplifyServerContext helper function created by calling the createServerRunner function exported from @aws-amplify/adapter-nextjs to call the Amplify API in an isolated server context.

For the GraphQL API category, review Connect to GraphQL API from server-side runtimes.

Note: A subset of Amplify APIs can now be called on the server side of a Next.js app. These APIs are exported from the /server sub paths. See the full list of supported APIs.

Note: If you use the Amplify server-side APIs in a server action and encounter the following error running next build:

./node_modules/@aws-amplify/core/node_modules/@aws-crypto/sha256-js/build/module/index.js + 12 modules

Cannot get final name for export 'fromUtf8' of ./node_modules/@smithy/util-utf8/dist-es/index.js

You can add the following to your next.config.js:

See Next.js documentation on serverComponentsPackages for more details.

With Next.js App Router In React Server Component Dynamic Rendering

Dynamic rendering is based on a user session extracted from an incoming request.

Static Rendering

Static rendering doesn’t require a user session, so you can specify the nextServerContext parameter as null. This is useful for some use cases, for example, when you are using the Storage API with guest access (if you have enabled it in your backend).

Note: The URL returned by the getUrl API expires in the above example. You may want to specify the revalidate parameter to rerender the page as required to ensure the URL gets regenerated.

In Route Handlers

Take implementing an API route that enables GET /apis/get-current-user.

When you call fetch('/apis/get-current-user') it return a payload that contains the user data for the currently signed-in user.

With Next.js Pages Router In getServerSideProps

The following example extracts current user data from the request and provides them to a page react component via its props.

In getStaticProps

Similar to static rendering with the App Router, you can pass null as the value of the nextServerContext parameter to use the Amplify Storage API with guest access.

Supported APIs for Next.js server-side usage

All APIs that support use on the server are exported from the aws-amplify/<category>/server sub paths. You must use these APIs for any server side use cases.

Migrate from Amplify JavaScript v5

The Amplify JS v5 withSSRContext utility is no longer available with Amplify JS v6. You will need to use the createServerRunner function exported from @aws-amplify/adapter-nextjs to create a runWithAmplifyServerContext function, and use this function to make Amplify API calls on the server side of your Next.js app. For usage examples, see here.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4