Skip to content

Commit b2b68b6

Browse files
authored
feat: Implement logout functionality for Gen 2 RSC Quickstart (#6839)
* update RSC quickstart with logout functionality * make option plural per feedback * add a section to have callback urls redirect to `/login` for Social Providers.
1 parent 0e6cb4e commit b2b68b6

File tree

1 file changed

+89
-22
lines changed
  • src/pages/gen2/start/quickstart/nextjs-app-router-server-components

1 file changed

+89
-22
lines changed

src/pages/gen2/start/quickstart/nextjs-app-router-server-components/index.mdx

Lines changed: 89 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,51 @@ export default function RootLayout({
9494
}
9595
```
9696

97-
### Add a login page
97+
### Configure Amplify Server Side
98+
99+
First, install the Amplify Next.js Adapter:
100+
101+
```bash
102+
npm install @aws-amplify/adapter-nextjs
103+
```
104+
105+
Next, create a `utils/amplify-utils.ts` file from the root of the project and paste the code below. `runWithAmplifyServerContext`, `cookiesClient` and `AuthGetCurrentUserServer` are declared here and will be used to gain access to Amplify assets from the server.
106+
107+
```ts title="utils/amplify-utils.ts"
108+
// utils/amplify-utils.ts
109+
import { cookies } from "next/headers";
110+
111+
import { createServerRunner } from "@aws-amplify/adapter-nextjs";
112+
import { generateServerClientUsingCookies } from "@aws-amplify/adapter-nextjs/api";
113+
import { getCurrentUser } from "aws-amplify/auth/server";
114+
115+
import { type Schema } from "@/amplify/data/resource";
116+
import config from "@/amplifyconfiguration.json";
117+
118+
export const { runWithAmplifyServerContext } = createServerRunner({
119+
config,
120+
});
121+
122+
export const cookiesClient = generateServerClientUsingCookies<Schema>({
123+
config,
124+
cookies,
125+
});
126+
127+
export async function AuthGetCurrentUserServer() {
128+
try {
129+
const currentUser = await runWithAmplifyServerContext({
130+
nextServerContext: { cookies },
131+
operation: (contextSpec) => getCurrentUser(contextSpec),
132+
});
133+
return currentUser;
134+
} catch (error) {
135+
console.error(error);
136+
}
137+
}
138+
```
139+
140+
141+
### Add Server Authentication Routes
98142

99143
First, create a client side Login component in the `components` folder that will be wrapped in `withAuthenticator`. If the user is logged in, they will be redirected to the index route, otherwise the [Amplify UI Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator) will be rendered.
100144

@@ -133,7 +177,7 @@ export default function LoginPage() {
133177

134178
<Accordion title="Custom <Authenticator> example">
135179

136-
Some applications require more customization for the `<Authenticator>` component. The following example shows how to add a custom Header to the `<Authenticator>`. For this use, you will not need the `Login` file in the `components` folder but can do everything through the `page` file in the `app/login/` folder. For more customization option, see [Authenticator Customization](https://ui.docs.amplify.aws/react/connected-components/authenticator/customization).
180+
Some applications require more customization for the `<Authenticator>` component. The following example shows how to add a custom Header to the `<Authenticator>`. For this use, you will not need the `Login` file in the `components` folder but can do everything through the `page` file in the `app/login/` folder. For more customization options, see [Authenticator Customization](https://ui.docs.amplify.aws/react/connected-components/authenticator/customization).
137181

138182
```ts title="app/login/page.tsx"
139183
// app/login/page.tsx - Custom <Authenticator>
@@ -184,37 +228,56 @@ export default function Login() {
184228
</Accordion>
185229

186230

187-
### Configure Amplify Server Side
231+
Finally, create a `Logout` component to be used later.
188232

189-
First, install the Amplify Next.js Adapter:
233+
```ts title="components/Logout.tsx"
234+
// components/Logout.tsx
190235

191-
```bash
192-
npm install @aws-amplify/adapter-nextjs
193-
```
236+
"use client";
194237

195-
Next, create a `utils/amplify-utils.ts` file from the root of the project and paste the code below. `runWithAmplifyServerContext` and `cookiesClient` are declared here and will be used to gain access to Amplify assets from the server.
238+
import { signOut } from "aws-amplify/auth";
239+
import { useRouter } from "next/navigation";
196240

241+
export default function Logout() {
242+
const router = useRouter();
197243

198-
```ts title="utils/amplify-utils.ts"
199-
// utils/amplify-utils.ts
200-
import { cookies } from "next/headers";
244+
return (
245+
<button
246+
onClick={async () => {
247+
await signOut();
248+
router.push("/login");
249+
}}
250+
className="px-2 bg-white text-black"
251+
>
252+
Sign out
253+
</button>
254+
);
255+
}
256+
```
201257

202-
import { createServerRunner } from "@aws-amplify/adapter-nextjs";
203-
import { generateServerClientUsingCookies } from "@aws-amplify/adapter-nextjs/api";
258+
<Callout info>
204259

205-
import { type Schema } from "@/amplify/data/resource";
206-
import config from "@/amplifyconfiguration.json";
260+
**Note**: If using [Amplify UI Social Providers](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#social-providers), set the `callbackUrls` for the `/login` route when [configuring social sign-in for your Gen 2 backend](https://docs.amplify.aws/gen2/build-a-backend/auth/add-social-provider/#configure-social-sign-in-backend), as shown below.
207261

208-
export const { runWithAmplifyServerContext } = createServerRunner({
209-
config,
210-
});
262+
```ts title="amplify/auth/resource.ts"
263+
import { defineAuth, secret } from '@aws-amplify/backend';
211264

212-
export const cookiesClient = generateServerClientUsingCookies<Schema>({
213-
config,
214-
cookies,
265+
export const auth = defineAuth({
266+
loginWith: {
267+
externalProviders: {
268+
// ...
269+
callbackUrls: [
270+
'http://localhost:3000/login',
271+
'https://mywebsite.com/login'
272+
],
273+
logoutUrls: ['http://localhost:3000/logout', 'https://mywebsite.com/logout']
274+
}
275+
}
215276
});
216277
```
217278

279+
</Callout>
280+
218281
### Add middleware for server-side redirect
219282

220283
Create `middleware.ts` in the root of the project with the contents below.
@@ -312,9 +375,12 @@ After creating a todo, `revalidatePath` is run to clear the Next.js cache for th
312375

313376
import { revalidatePath } from "next/cache";
314377

315-
import { cookiesClient } from "@/utils/amplify-utils";
378+
import { AuthGetCurrentUserServer, cookiesClient } from "@/utils/amplify-utils";
379+
380+
import Logout from "@/components/Logout";
316381

317382
async function App() {
383+
const user = await AuthGetCurrentUserServer();
318384
const { data: todos } = await cookiesClient.models.Todo.list();
319385

320386
async function addTodo(data: FormData) {
@@ -331,6 +397,7 @@ async function App() {
331397
return (
332398
<>
333399
<h1>Hello, Amplify 👋</h1>
400+
{user && <Logout />}
334401
<form action={addTodo}>
335402
<input type="text" name="title" />
336403
<button type="submit">Add Todo</button>

0 commit comments

Comments
 (0)