Skip to content

Commit 8445d87

Browse files
committed
chore: rearrange content sectioins
1 parent 4db9f25 commit 8445d87

File tree

2 files changed

+187
-153
lines changed
  • src/pages
    • [platform]/build-a-backend/server-side-rendering
    • gen1/[platform]/build-a-backend/server-side-rendering/nextjs

2 files changed

+187
-153
lines changed

src/pages/[platform]/build-a-backend/server-side-rendering/index.mdx

Lines changed: 99 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,28 @@ Before you begin:
3838

3939
## Install the Amplify Next.js adapter
4040

41+
<Callout warning>
42+
43+
**Note:** Amplify JS v6 supports Next.js with the version range: `>=13.5.0 <16.0.0`.
44+
Ensure you have the correct version to integrate with Amplify.
45+
46+
</Callout>
47+
4148
To use Amplify APIs server-side, you need to install the Amplify Next.js adapter in addition to the Amplify libraries:
4249

4350
```bash title="Terminal" showLineNumbers={false}
4451
npm add aws-amplify @aws-amplify/adapter-nextjs
4552
```
4653

47-
## Configure Amplify APIs for server-side usage
54+
## Configure Amplify in Next.js
4855

49-
You will need to create a `runWithAmplifyServerContextRunner` function to use Amplify APIs on the server-side of your Next.js app.
56+
<BlockSwitcher>
57+
58+
<Block name="Configure Amplify for server-side usage">
5059

51-
You can create an `amplifyServerUtils.ts` file under a `utils` folder in your codebase. In this file, you will import the Amplify backend outputs from the `amplify_outputs.json` file that is generated by the Amplify CLI, and use the `createServerRunner` function to create the `runWithAmplifyServerContextRunner` function.
60+
You will need to create a `runWithAmplifyServerContext` function to use Amplify APIs on the server-side of your Next.js app.
61+
62+
You can create an `amplifyServerUtils.ts` file under a `utils` folder in your codebase. In this file, you will import the Amplify backend outputs from the `amplify_outputs.json` file that is generated by the Amplify CLI, and use the `createServerRunner` function to create the `runWithAmplifyServerContext` function.
5263

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

@@ -64,16 +75,21 @@ export const { runWithAmplifyServerContext } = createServerRunner({
6475
You can use the exported `runWithAmplifyServerContext` function to call Amplify APIs within isolated request contexts. You can review examples under the [Calling Amplify category APIs on the server side](#calling-amplify-category-apis-on-the-server-side) section.
6576

6677
<Callout>
67-
**TIP:** You only need to call the `createServerRunner` function once and reuse the `runWithAmplifyServerContext` function throughout.
78+
**Tip:** You only need to call the `createServerRunner` function once and reuse the `runWithAmplifyServerContext` function throughout.
6879
</Callout>
6980

70-
## Configure Amplify library for client-side usage
81+
</Block>
82+
<Block name="Configure Amplify for client-side usage">
83+
84+
<Callout>
85+
**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.
86+
</Callout>
7187

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

7490
<Callout>
7591

76-
**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+
**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.
7793

7894
</Callout>
7995

@@ -96,6 +112,12 @@ export default function RootLayoutThatConfiguresAmplifyOnTheClient({
96112
}
97113
```
98114

115+
<Callout warning>
116+
117+
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.
118+
119+
</Callout>
120+
99121
<Callout>
100122

101123
To avoid repetitive calls to `Amplify.configure`, you can call it once in a top-level client-side rendered layout component.
@@ -154,79 +176,25 @@ export default function RootLayout({
154176

155177
</Accordion>
156178

157-
## Authentication with Next.js server-side runtime
158-
159-
You can use the Amplify Auth category APIs to sign up and sign in your end users on the client side. When you set `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.
160-
161-
### Manage Auth session with the Next.js Middleware
162-
163-
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:
164-
165-
```typescript title="src/middleware.ts"
166-
import { fetchAuthSession } from 'aws-amplify/auth/server';
167-
import { NextRequest, NextResponse } from 'next/server';
168-
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';
169-
170-
export async function middleware(request: NextRequest) {
171-
const response = NextResponse.next();
172-
173-
const authenticated = await runWithAmplifyServerContext({
174-
nextServerContext: { request, response },
175-
operation: async (contextSpec) => {
176-
try {
177-
const session = await fetchAuthSession(contextSpec);
178-
return (
179-
session.tokens?.accessToken !== undefined &&
180-
session.tokens?.idToken !== undefined
181-
);
182-
} catch (error) {
183-
console.log(error);
184-
return false;
185-
}
186-
}
187-
});
188-
189-
if (authenticated) {
190-
return response;
191-
}
192-
193-
return NextResponse.redirect(new URL('/sign-in', request.url));
194-
}
195-
196-
export const config = {
197-
matcher: [
198-
/*
199-
* Match all request paths except for the ones starting with:
200-
* - api (API routes)
201-
* - _next/static (static files)
202-
* - _next/image (image optimization files)
203-
* - favicon.ico (favicon file)
204-
*/
205-
'/((?!api|_next/static|_next/image|favicon.ico|sign-in).*)'
206-
]
207-
};
208-
```
179+
</Block>
209180

210-
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.
181+
</BlockSwitcher>
211182

212-
<Callout>
213183

214-
**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.
215184

216-
</Callout>
185+
## Authentication with Next.js server-side runtime
217186

218187
### (Experimental) Perform authentication on the server side and enable HttpOnly cookies
219188

220189
<Callout warning>
221190

222-
**Warning:** 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](/[platform]/build-a-backend/server-side-rendering/#supported-apis-for-nextjs-server-side-usage) on the server side.
223-
224-
</Callout>
191+
**Warning:** This feature is experimental and may change in future releases.
225192

226-
**Prerequisites**
193+
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](/[platform]/build-a-backend/server-side-rendering/#supported-apis-for-nextjs-server-side-usage) on the server side.
227194

228-
To authenticate users on the server side, you must enable either Amazon Cognito Managed Login or Hosted UI in your Amazon Cognito User Pool client.
195+
</Callout>
229196

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

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

@@ -322,17 +290,18 @@ You can provide the callback API routes as the redirect URLs in the Auth resourc
322290
export const auth = defineAuth({
323291
loginWith: {
324292
email: true,
293+
// highlight-start
325294
externalProviders: {
326-
google: {/* ... */},
327-
// highlight-start
328295
callbackUrls: ["https://myapp.com/api/auth/sign-in-callback"],
329296
logoutUrls: ["https://myapp.com/api/auth/sign-out-callback"],
330-
// highlight-end
331297
},
298+
// highlight-end
332299
},
333300
});
334301
```
335302

303+
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.
304+
336305
#### Step 5 - Use Anchor link for initiating server-side authentication flows
337306

338307
Use HTML anchor links to navigate users to the sign-in and sign-up routes. For example:
@@ -386,6 +355,63 @@ export const SignOutButton() {
386355

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

358+
### Validate user session with the Next.js Middleware
359+
360+
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:
361+
362+
```typescript title="src/middleware.ts"
363+
import { fetchAuthSession } from 'aws-amplify/auth/server';
364+
import { NextRequest, NextResponse } from 'next/server';
365+
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';
366+
367+
export async function middleware(request: NextRequest) {
368+
const response = NextResponse.next();
369+
370+
const authenticated = await runWithAmplifyServerContext({
371+
nextServerContext: { request, response },
372+
operation: async (contextSpec) => {
373+
try {
374+
const session = await fetchAuthSession(contextSpec);
375+
return (
376+
session.tokens?.accessToken !== undefined &&
377+
session.tokens?.idToken !== undefined
378+
);
379+
} catch (error) {
380+
console.log(error);
381+
return false;
382+
}
383+
}
384+
});
385+
386+
if (authenticated) {
387+
return response;
388+
}
389+
390+
return NextResponse.redirect(new URL('/sign-in', request.url));
391+
}
392+
393+
export const config = {
394+
matcher: [
395+
/*
396+
* Match all request paths except for the ones starting with:
397+
* - api (API routes)
398+
* - _next/static (static files)
399+
* - _next/image (image optimization files)
400+
* - favicon.ico (favicon file)
401+
*/
402+
'/((?!api|_next/static|_next/image|favicon.ico|sign-in).*)'
403+
]
404+
};
405+
```
406+
407+
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.
408+
409+
<Callout>
410+
411+
**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.
412+
413+
</Callout>
414+
389415
## Calling Amplify category APIs on the server side
390416

391417
For the **Auth** categories to use Amplify APIs on the server in your Next.js app, you will need to:
@@ -397,7 +423,7 @@ For the **GraphQL API** category, review [Connect to data from Server-side Runti
397423

398424
<Callout>
399425

400-
**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.
426+
**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.
401427

402428
</Callout>
403429

@@ -445,10 +471,7 @@ export default async function AuthGetCurrentUserServer() {
445471
});
446472

447473
return (
448-
<AuthFetchResult
449-
description="The API is called on the server side."
450-
data={currentUser}
451-
/>
474+
<p>{`Hello, ${currentUser.username}`}</p>
452475
);
453476
} catch (error) {
454477
console.error(error);
@@ -496,7 +519,7 @@ export default async function StaticallyRenderedPage() {
496519

497520
<Callout>
498521

499-
**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.
522+
**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.
500523

501524
</Callout>
502525

0 commit comments

Comments
 (0)