` | Upon navigating an end user to this route, they’ll be redirected first to the Amazon Cognito Managed Login and then the specified social provider sign-in page. After sign-in, they’ll be redirected back to the route `/api/auth/sign-in-callback`. |
+| `/api/auth/sign-out` | Upon navigating an end user to this route, the end user will be signed out and redirected to the route `/api/auth/sign-out-callback`. |
+| `/api/auth/sign-in-callback` | Amazon Cognito Managed Login redirects an end user back to this route after signing in. Amplify exchanges auth tokens and stores them as HttpOnly cookies in the browser cookie store, then redirects the end user back to the route specified by the `redirectOnSignInComplete` parameter. |
+| `/api/auth/sign-out-callback` | Amazon Cognito Managed Login redirects an end user back to this route after signing out, Amplify revokes access token and refresh token and removes token cookies from browser cookie store, then redirects the end user back to the route specified by the `redirectOnSignOutComplete` parameter. |
+
+
+
+**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 provide the callback API routes as the redirect URLs in the Auth resource configuration. For example:
+
+```ts title="amplify/auth/resource.ts"
+export const auth = defineAuth({
+ loginWith: {
+ email: true,
+ // highlight-start
+ externalProviders: {
+ callbackUrls: ["https://myapp.com/api/auth/sign-in-callback"],
+ logoutUrls: ["https://myapp.com/api/auth/sign-out-callback"],
+ },
+ // highlight-end
+ },
+});
+```
+
+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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html) for more information.
+
+#### Step 5 - Use Anchor link for initiating server-side authentication flows
-### Manage Auth session with the Next.js Middleware
+Use HTML anchor links to navigate users to the sign-in and sign-up routes. For example:
+
+
+
+```tsx title="src/components/SignInButton.tsx"
+export const SignInButton() {
+ return (
+
+ Sign In
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignInWithGoogleButton.tsx"
+export const SignInWithGoogleButton() {
+ return (
+
+ Sign In with Google
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignUpButton.tsx"
+export const SignUpButton() {
+ return (
+
+ Sign Up
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignOutButton.tsx"
+export const SignOutButton() {
+ return (
+
+ Sign Out
+
+ );
+}
+```
+
+
+
+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:
-```typescript
+```typescript title="src/middleware.ts"
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { NextRequest, NextResponse } from 'next/server';
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';
@@ -211,7 +412,7 @@ In this example, if the incoming request is not associated with a valid user ses
-**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.
+**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.
@@ -226,7 +427,7 @@ For the **GraphQL API** category, review [Connect to data from Server-side Runti
-**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](#supported-apis-for-nextjs-server-side-usage) of supported APIs.
+**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](#supported-apis-for-nextjs-server-side-usage) of supported APIs.
@@ -274,10 +475,7 @@ export default async function AuthGetCurrentUserServer() {
});
return (
-
+ {`Hello, ${currentUser.username}`}
);
} catch (error) {
console.error(error);
@@ -325,7 +523,7 @@ export default async function StaticallyRenderedPage() {
-**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.
+**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.
diff --git a/src/pages/gen1/[platform]/build-a-backend/server-side-rendering/nextjs/index.mdx b/src/pages/gen1/[platform]/build-a-backend/server-side-rendering/nextjs/index.mdx
index f10af2674ac..11fc551dfe3 100644
--- a/src/pages/gen1/[platform]/build-a-backend/server-side-rendering/nextjs/index.mdx
+++ b/src/pages/gen1/[platform]/build-a-backend/server-side-rendering/nextjs/index.mdx
@@ -32,7 +32,7 @@ This guide walks through how to use Amplify Auth, GraphQL API, REST API, and Sto
-**NOTE:** Amplify JS v6 supports Next.js with the version range: `>=13.5.0 <16.0.0`.
+**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.
@@ -42,15 +42,19 @@ Before you begin, you will need:
- [A Next.js application created](/gen1/[platform]/start/project-setup/create-application/)
- [Installed Amplify libraries for Next.js](/gen1/[platform]/start/project-setup/create-application/#install-amplify-libraries)
-## Configure Amplify Library for server-side usage
+## Configure Amplify in Next.js
-To use Amplify APIs on the server-side of your Next.js app, you will need to create a `runWithAmplifyServerContextRunner` function.
+
-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 `runWithAmplifyServerContextRunner` function.
+
+
+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:
-```typescript
+```typescript title="src/utils/amplifyServerUtils.ts"
import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import config from '@/amplifyconfiguration.json';
@@ -61,15 +65,22 @@ export const { runWithAmplifyServerContext } = createServerRunner({
You can use the exported `runWithAmplifyServerContext` function to call Amplify APIs with in isolated request contexts. Usage examples see [here](#calling-amplify-category-apis-on-the-server-side).
-**TIP:** You only need to call the `createServerRunner` function once and reuse the `runWithAmplifyServerContext` function throughout.
+
+**Tip:** You only need to call the `createServerRunner` function once and reuse the `runWithAmplifyServerContext` function throughout.
+
-## Configure Amplify library for client-side usage
+
+
+
+
+**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.
+**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.
@@ -92,7 +103,7 @@ export default function RootLayoutThatConfiguresAmplifyOnTheClient({
}
```
-
+
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](/gen1/[platform]/build-a-backend/troubleshooting/library-not-configured/) for possible causes of this issue.
@@ -108,9 +119,9 @@ To avoid repetitive calls to `Amplify.configure`, you can call it once in a top-
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.ts`:
+`ConfigureAmplifyClientSide.tsx`:
-```typescript
+```tsx title="src/components/client/ConfigureAmplifyClientSide.tsx"
'use client';
import { Amplify } from 'aws-amplify';
@@ -125,7 +136,7 @@ export default function ConfigureAmplifyClientSide() {
`layout.tsx`:
-```jsx
+```tsx title="src/app/layout.tsx"
import ConfigureAmplifyClientSide from '@/components/ConfigureAmplifyClientSide';
import './globals.css';
@@ -156,15 +167,186 @@ export default function RootLayout({
+
+
+
+
## Authentication with Next.js server-side runtime
-You can use the Amplify Auth category APIs to sign up and sign in your end users on the client side. With setting `ssr: true` when calling `Amplify.configure`, the Amplify library uses cookies to store tokens, which will be sent along with HTTP requests to your Next.js app server.
+### (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](/gen1/[platform]/build-a-backend/server-side-rendering/nextjs/#supported-apis-for-nextjs-server-side-usage) 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:
+
+```shell title=".env" showLineNumbers={false}
+AMPLIFY_APP_ORIGIN=https://myapp.com
+```
+
+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.
+
+```typescript title="src/utils/amplifyServerUtils.ts"
+import { createServerRunner } from '@aws-amplify/adapter-nextjs';
+import config from '@/amplifyconfiguration.json';
+
+export const {
+ runWithAmplifyServerContext,
+ // highlight-start
+ createAuthRouteHandlers,
+ // highlight-end
+} = createServerRunner({
+ config,
+ // highlight-start
+ runtimeOptions: {
+ cookies: {
+ domain: '.myapp.com', // making cookies available to all subdomains
+ sameSite: 'strict',
+ maxAge: 60 * 60 * 24 * 7 // 7 days
+ }
+ }
+ // highlight-end
+});
+```
+
+#### Step 3 - Set up the Auth API routes
+
+Create an API route using the `createAuthRouteHandlers` function. For example:
+
+
+
+```typescript title="src/app/api/auth/[slug]/route.ts"
+import { createAuthRouteHandlers } from "@/utils/amplifyServerUtils";
+
+export const GET = createAuthRouteHandlers({
+ redirectOnSignInComplete: "/home",
+ redirectOnSignOutComplete: "/sign-in",
+});
+```
+
+
+```typescript title="src/pages/api/auth/[slug].ts"
+import { createAuthRouteHandlers } from "@/utils/amplifyServerUtils";
+
+export default createAuthRouteHandlers({
+ redirectOnSignInComplete: "/home",
+ redirectOnSignOutComplete: "/sign-in",
+});
+```
+
+
+
+With the above example, Amplify generates the following API routes:
+
+| API Routes | What it does |
+| --------------------------------------------------- | ------------------------------------------------------------ |
+| `/api/auth/sign-up` | Upon navigating an end user to this route, they’ll be redirected to the Amazon Cognito Managed Login sign-up form. After sign-up and sign-in, they’ll be redirected back to the route `/api/auth/sign-in-callback`. |
+| `/api/auth/sign-in` | Upon navigating an end user to this route, they’ll be redirected to the Amazon Cognito Managed Login sign-in form. After sign-in, they’ll be redirected back to the route `/api/auth/sign-in-callback`. |
+| `/api/auth/sign-in?provider=` | Upon navigating an end user to this route, they’ll be redirected first to the Amazon Cognito Managed Login and then the specified social provider sign-in page. After sign-in, they’ll be redirected back to the route `/api/auth/sign-in-callback`. |
+| `/api/auth/sign-out` | Upon navigating an end user to this route, the end user will be signed out and redirected to the route `/api/auth/sign-out-callback`. |
+| `/api/auth/sign-in-callback` | Amazon Cognito Managed Login redirects an end user back to this route after signing in. Amplify exchanges auth tokens and stores them as HttpOnly cookies in the browser cookie store, then redirects the end user back to the route specified by the `redirectOnSignInComplete` parameter. |
+| `/api/auth/sign-out-callback` | Amazon Cognito Managed Login redirects an end user back to this route after signing out, Amplify revokes access token and refresh token and removes token cookies from browser cookie store, then redirects the end user back to the route specified by the `redirectOnSignOutComplete` parameter. |
+
+
+
+**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](/gen1/[platform]/build-a-backend/auth/add-social-provider/#configure-the-auth-category) for more details. With the above example, you can provide the following redirect URLs:
+
+```text showLineNumbers={false}
+// redirect signin URI:
+https://myapp.com/api/auth/sign-in-callback
+
+// redirect signout URI:
+https://myapp.com/api/auth/sign-out-callback
+```
+
+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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html) for more information.
+
+#### Step 5 - Use Anchor link for initiating server-side authentication flows
-### Manage Auth session with the Next.js Middleware
+Use HTML anchor links to navigate users to the sign-in and sign-up routes. For example:
+
+
+
+```tsx title="src/components/SignInButton.tsx"
+export const SignInButton() {
+ return (
+
+ Sign In
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignInWithGoogleButton.tsx"
+export const SignInWithGoogleButton() {
+ return (
+
+ Sign In with Google
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignUpButton.tsx"
+export const SignUpButton() {
+ return (
+
+ Sign Up
+
+ );
+}
+```
+
+
+```tsx title="src/components/SignOutButton.tsx"
+export const SignOutButton() {
+ return (
+
+ Sign Out
+
+ );
+}
+```
+
+
+
+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:
-```typescript
+```typescript title="src/middleware.ts"
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { NextRequest, NextResponse } from 'next/server';
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';
@@ -213,7 +395,7 @@ In this example, if the incoming request is not associated with a valid user ses
-**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.
+**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.
@@ -228,7 +410,7 @@ For the **GraphQL API** category, review [Connect to GraphQL API from server-sid
-**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](#supported-apis-for-nextjs-server-side-usage) of supported APIs.
+**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](#supported-apis-for-nextjs-server-side-usage) of supported APIs.
@@ -278,10 +460,7 @@ export default async function AuthGetCurrentUserServer() {
});
return (
-
+ {`Hello, ${currentUser.username}`}
);
} catch (error) {
console.error(error);
@@ -329,7 +508,7 @@ export default async function StaticallyRenderedPage() {
-**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.
+**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.