Skip to content

Commit 2f9d1bb

Browse files
Next.js auth tutorial update (#21866)
* New reference architecture diagram: Storing user generated content * Apply suggestions from code review * Fix broken links * Update fullstack authentication tutorial for Next.js and Cloudflare D1 - Clarified instructions for modifying `tsconfig.json` and `cloudflare-env.d.ts`. - Added note about wrangler creating the worker if not deployed. - Improved error handling in the GET function. - Updated file references for clarity and consistency. * Update fullstack authentication tutorial for Next.js. Adjusted the tutorial's update date, refined package manager arguments, and added notes on D1 database creation and Windows support. * Refactor getCloudflareContext calls to use async option --------- Co-authored-by: Jun Lee <[email protected]>
1 parent e08af69 commit 2f9d1bb

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

src/content/docs/developer-spotlight/tutorials/fullstack-authentication-with-next-js-and-cloudflare-d1.mdx

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
updated: 2025-01-13
2+
updated: 2025-04-21
33
difficulty: Intermediate
44
pcx_content_type: tutorial
55
title: Setup Fullstack Authentication with Next.js, Auth.js, and Cloudflare D1
@@ -46,7 +46,7 @@ From within the repository or directory where you want to create your project ru
4646
<PackageManagers
4747
type="create"
4848
pkg="cloudflare@latest"
49-
args={"auth-js-d1-example --framework=next --experimental"}
49+
args={"auth-js-d1-example --framework=next"}
5050
/>
5151

5252
<Render
@@ -60,7 +60,7 @@ From within the repository or directory where you want to create your project ru
6060

6161
This will create a new Next.js project using [OpenNext](https://opennext.js.org/cloudflare) that will run in a Worker using [Workers Static Assets](/workers/frameworks/framework-guides/nextjs/#static-assets).
6262

63-
Before we get started, open your project's `tsconfig.json` file and add the following to the `compilerOptions` object to allow for top level await needed to let our application get the Cloudflare context:
63+
Before we get started, open your project's `tsconfig.json` file and modify the following to the `compilerOptions` object to allow for top level await needed to let our application get the Cloudflare context:
6464

6565
```json title="tsconfig.json"
6666
{
@@ -101,6 +101,8 @@ Now, deviating from the standard Auth.js setup, locate your generated secret (li
101101
npx wrangler secret put AUTH_SECRET
102102
```
103103

104+
If you have not deployed yet that's fine. Allow wrangler to create the worker for you.
105+
104106
After adding the secret, update your `.dev.vars` file to include an `AUTH_SECRET` value (this secret should be different from the one you generated earlier for security purposes):
105107

106108
```sh title=".dev.vars"
@@ -109,9 +111,9 @@ AUTH_SECRET = "<replace-me>"
109111
# ...
110112
```
111113

112-
Next, go into the newly generated `env.d.ts` file and add the following to the <Type text="CloudflareEnv" /> interface:
114+
Next, go into `cloudflare-env.d.ts` file and add the following to the <Type text="CloudflareEnv" /> interface:
113115

114-
```ts title="env.d.ts"
116+
```ts title="cloudflare-env.d.ts"
115117
interface CloudflareEnv {
116118
AUTH_SECRET: string;
117119
}
@@ -144,9 +146,9 @@ database_id = "<unique-ID-for-your-database>"
144146

145147
</WranglerConfig>
146148

147-
Now, within your `env.d.ts`, add your D1 binding, like:
149+
Now, within your `cloudflare-env.d.ts`, add your D1 binding, like:
148150

149-
```ts title="env.d.ts"
151+
```ts title="cloudflare-env.d.ts"
150152
interface CloudflareEnv {
151153
DB: D1Database;
152154
AUTH_SECRET: string;
@@ -185,9 +187,9 @@ AUTH_RESEND_KEY = "<replace-me>"
185187
# ...
186188
```
187189

188-
After adding both of those Secrets, your `env.d.ts` should now include the following:
190+
After adding both of those Secrets, your `cloudflare-env.d.ts` should now include the following:
189191

190-
```ts title="env.d.ts"
192+
```ts title="cloudflare-env.d.ts"
191193
interface CloudflareEnv {
192194
DB: D1Database;
193195
AUTH_SECRET: string;
@@ -210,11 +212,11 @@ const authResult = async (): Promise<NextAuthResult> => {
210212
return NextAuth({
211213
providers: [
212214
Resend({
213-
apiKey: (await getCloudflareContext()).env.AUTH_RESEND_KEY,
214-
from: (await getCloudflareContext()).env.AUTH_EMAIL_FROM,
215+
apiKey: (await getCloudflareContext({async: true})).env.AUTH_RESEND_KEY,
216+
from: (await getCloudflareContext({async: true})).env.AUTH_EMAIL_FROM,
215217
}),
216218
],
217-
adapter: D1Adapter((await getCloudflareContext()).env.DB),
219+
adapter: D1Adapter((await getCloudflareContext({async: true})).env.DB),
218220
});
219221
};
220222

@@ -234,7 +236,7 @@ export const { GET, POST } = handlers;
234236
```
235237
</TypeScriptExample>
236238

237-
Now, within the `src/` directory, create a `middleware.ts` file to persist session data containing the following:
239+
Now, within the `src/` directory, create a `middleware.ts` file. If you do not have a `src/` directory, create a `middleware.ts` file in the root of your project. This will persist session data.
238240

239241
<TypeScriptExample filename="src/middleware.ts">
240242
```ts
@@ -248,15 +250,17 @@ The D1 adapter requires that tables be created within your database. It [recomme
248250

249251
<TypeScriptExample filename="src/app/api/setup/route.ts">
250252
```ts
251-
import type { NextRequest } from 'next/server';
252253
import { up } from "@auth/d1-adapter";
253254
import { getCloudflareContext } from "@opennextjs/cloudflare";
254255

255-
export async function GET(request: NextRequest) {
256+
export async function GET() {
256257
try {
257-
await up((await getCloudflareContext()).env.DB)
258-
} catch (e: any) {
259-
console.log(e.cause.message, e.message)
258+
await up((await getCloudflareContext({async: true})).env.DB)
259+
} catch (e: unknown) {
260+
if (e instanceof Error) {
261+
const causeMessage = e.cause instanceof Error ? e.cause.message : String(e.cause);
262+
console.log(causeMessage, e.message)
263+
}
260264
}
261265
return new Response('Migration completed');
262266
}
@@ -283,7 +287,7 @@ Before we go further, make sure you've created all of the necessary files:
283287
- auth.ts
284288
- page.ts
285289
- middleware.ts
286-
- env.d.ts
290+
- cloudflare-env.d.ts
287291
- wrangler.toml
288292
</FileTree>
289293

@@ -324,7 +328,7 @@ async function updateName(formData: FormData): Promise<void> {
324328
return;
325329
}
326330
const query = `UPDATE users SET name = $1 WHERE id = $2`;
327-
await updateRecord((await getCloudflareContext()).env.DB, query, [name, session.user.id]);
331+
await updateRecord((await getCloudflareContext({async: true})).env.DB, query, [name, session.user.id]);
328332
redirect('/');
329333
}
330334

@@ -420,6 +424,8 @@ Now, it's time to preview our app. Run the following to preview your application
420424

421425
:::caution[Windows support]
422426
OpenNext has [limited Windows support](https://opennext.js.org/cloudflare#windows-support) and recommends using WSL2 if developing on Windows.
427+
428+
Also, you may need to comment out the `@import "tw-animate-css"` line in the `globals.css` file.
423429
:::
424430

425431
You should see our login form. But wait, we're not done yet. Remember to create your database tables by visiting `/api/setup`. You should see `Migration completed`. This means your database is ready to go.
@@ -441,6 +447,10 @@ npx wrangler secret put AUTH_URL
441447

442448
After the changes are deployed, you should now be able to access and try out your new application.
443449

450+
:::note[D1 Database Creation]
451+
You will need to hit the `/api/setup` on your deployed URL to create the necessary tables in your D1 database. It will create 4 tables if they don’t already exist: `accounts`, `sessions`, `users`, and `verification_tokens`. If the `api/setup` route is not working, you can also initialize your tables manually. Look in [migrations.ts](https://github.com/nextauthjs/next-auth/blob/main/packages/adapter-d1/src/migrations.ts) of the Auth.js D1 adapter for the relevant SQL.
452+
:::
453+
444454
You have successfully created, configured, and deployed a fullstack Next.js application with authentication powered by Auth.js, Resend, and Cloudflare D1.
445455

446456
## Related resources

0 commit comments

Comments
 (0)