Skip to content

Commit d0cd80e

Browse files
aidankmcalistergithub-actions[bot]ankur-arch
authored
DC-5242 Astro Better-Auth Guide (#7215)
* doc created * nextjs betterauth fixed * guide broken down into manageable steps * image added * Optimised images with calibre/image-actions * image updated * Optimised images with calibre/image-actions * lychee only comments on broken links * config updated * lychee updated based on CR comment * chore: trigger CI checks * ignore gnu * fix: update naming to better-auth DC-6120 * Optimised images with calibre/image-actions * chore: shorten word --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Ankur Datta <[email protected]>
1 parent 25dbc36 commit d0cd80e

File tree

6 files changed

+976
-39
lines changed

6 files changed

+976
-39
lines changed

.github/workflows/lychee.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ jobs:
3434
--exclude 'http://localhost.*'
3535
--exclude 'https://localhost.*'
3636
--exclude 'https://cockroachlabs.com'
37+
--exclude 'https://www.gnu.org'
3738
--exclude '^/.*'
3839
'./**/*.md' './**/*.mdx'
3940
workingDirectory: "content"
@@ -60,6 +61,7 @@ jobs:
6061
--exclude 'http://localhost.*'
6162
--exclude 'https://localhost.*'
6263
--exclude 'https://cockroachlabs.com'
64+
--exclude 'https://www.gnu.org'
6365
--exclude '^/.*'
6466
'./**/*.md' './**/*.mdx'
6567
workingDirectory: "content"
@@ -97,7 +99,7 @@ jobs:
9799
fi
98100
99101
- name: 📝 Comment Broken Links
100-
if: ${{ always() && github.event.pull_request.head.repo.fork == false }}
102+
if: ${{ always() && github.event.pull_request.head.repo.fork == false && (steps.lychee.outputs.exit_code != 0 || (steps.lychee-retry.conclusion != 'skipped' && steps.lychee-retry.outputs.exit_code != 0)) }}
101103
uses: peter-evans/create-or-update-comment@v4
102104
with:
103105
issue-number: ${{ github.event.pull_request.number }}

content/800-guides/230-betterauth-nextjs.mdx

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
---
2-
title: 'How to use Prisma ORM with Better-Auth and Next.js'
3-
metaTitle: 'How to use Prisma ORM and Prisma Postgres with Better-Auth and Next.js'
4-
description: 'Learn how to use Prisma ORM in a Next.js app with Better-Auth'
5-
sidebar_label: 'Better-Auth (with Next.js)'
2+
title: 'How to use Prisma ORM with Better Auth and Next.js'
3+
metaTitle: 'How to use Prisma ORM and Prisma Postgres with Better Auth and Next.js'
4+
description: 'Learn how to use Prisma ORM in a Next.js app with Better Auth'
5+
sidebar_label: 'Better Auth (with Next.js)'
66
image: '/img/guides/prisma-betterauth-nextjs-cover.png'
77
completion_time: '25 min'
88
community_section: true
99
---
1010

1111
## Introduction
1212

13-
[Better-Auth](https://better-auth.com/) is a modern, open-source authentication solution for web applications. It's built with TypeScript, React, and Prisma to provide a simple and extensible auth experience.
13+
[Better Auth](https://better-auth.com/) is a modern, open-source authentication solution for web applications. It's built with TypeScript and provides a simple and extensible auth experience with support for multiple database adapters, including Prisma.
1414

15-
In this guide, you'll wire Better-Auth into a brand-new [Next.js](https://nextjs.org/) app and persist users in a [Prisma Postgres](https://prisma.io/postgres) database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/betterauth-nextjs).
15+
In this guide, you'll wire Better Auth into a brand-new [Next.js](https://nextjs.org/) app and persist users in a [Prisma Postgres](https://prisma.io/postgres) database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/betterauth-nextjs).
1616

1717
## Prerequisites
1818

@@ -78,15 +78,15 @@ Once installed, initialize Prisma in your project:
7878
npx prisma init --db --output ../src/generated/prisma
7979
```
8080
:::info
81-
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better-Auth Project"
81+
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better Auth Project"
8282
:::
8383

8484
This will create:
8585

86-
- A `prisma` directory with a `schema.prisma` file.
87-
- A Prisma Postgres database.
88-
- A `.env` file containing the `DATABASE_URL` at the project root.
89-
- An `output` directory for the generated Prisma Client as `better-auth/generated/prisma`.
86+
- A `prisma` directory with a `schema.prisma` file
87+
- A Prisma Postgres database
88+
- A `.env` file containing the `DATABASE_URL` at the project root
89+
- An `output` directory for the generated Prisma Client as `better-auth/generated/prisma`
9090

9191
### 2.2. Configure the Prisma client generator
9292

@@ -98,7 +98,7 @@ npx prisma generate
9898

9999
### 2.3. Set up a global Prisma client
100100

101-
Create a `/lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance.
101+
In the `src` directory, create a `lib` folder and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance.
102102

103103
```terminal
104104
mkdir -p src/lib
@@ -149,19 +149,19 @@ We recommend using a connection pooler (like [Prisma Accelerate](https://www.pri
149149
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
150150
:::
151151

152-
## 3. Set up Better-Auth
152+
## 3. Set up Better Auth
153153

154-
Now it's time to integrate Better-Auth for authentication.
154+
Now it's time to integrate Better Auth for authentication.
155155

156-
### 3.1. Install and configure Better-Auth
156+
### 3.1. Install and configure Better Auth
157157

158-
First, install the Better-Auth core package:
158+
First, install the Better Auth core package:
159159

160160
```terminal
161161
npm install better-auth
162162
```
163163

164-
Next, generate a secure secret that Better-Auth will use to sign authentication tokens. This ensures your tokens cannot be messed with.
164+
Next, generate a secure secret that Better Auth will use to sign authentication tokens. This ensures your tokens cannot be messed with.
165165

166166
```terminal
167167
npx @better-auth/cli@latest secret
@@ -170,7 +170,7 @@ npx @better-auth/cli@latest secret
170170
Copy the generated secret and add it, along with your application's URL, to your `.env` file:
171171

172172
```dotenv file=.env showLineNumbers
173-
# Better-Auth
173+
# Better Auth
174174
//add-start
175175
BETTER_AUTH_SECRET=your-generated-secret
176176
BETTER_AUTH_URL=http://localhost:3000
@@ -180,13 +180,13 @@ BETTER_AUTH_URL=http://localhost:3000
180180
DATABASE_URL="your-database-url"
181181
```
182182

183-
Now, create a configuration file for Better-Auth at `src/lib/auth.ts`:
183+
Now, create a configuration file for Better Auth. In the `src/lib` directory, create an `auth.ts` file:
184184

185185
```terminal
186186
touch src/lib/auth.ts
187187
```
188188

189-
In this file, you'll configure Better-Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication.
189+
In this file, you'll configure Better Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication.
190190

191191
```ts file=src/lib/auth.ts
192192
import { betterAuth } from 'better-auth'
@@ -200,7 +200,7 @@ export const auth = betterAuth({
200200
})
201201
```
202202

203-
Better-Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [documentation](https://www.better-auth.com/docs/authentication/email-password).
203+
Better Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [documentation](https://www.better-auth.com/docs/authentication/email-password).
204204

205205
```ts file=src/lib/auth.ts
206206
import { betterAuth } from 'better-auth'
@@ -240,9 +240,9 @@ export const auth = betterAuth({
240240
```
241241
:::
242242

243-
### 3.2. Add Better-Auth models to your schema
243+
### 3.2. Add Better Auth models to your schema
244244

245-
Better-Auth provides a CLI command to automatically add the necessary authentication models (`User`, `Session`, `Account`, and `Verification`) to your `schema.prisma` file.
245+
Better Auth provides a CLI command to automatically add the necessary authentication models (`User`, `Session`, `Account`, and `Verification`) to your `schema.prisma` file.
246246

247247
Run the following command:
248248

@@ -329,16 +329,16 @@ npx prisma migrate dev --name add-auth-models
329329

330330
## 4. Set up the API routes
331331

332-
Better-Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Next.js to handle all requests sent to `/api/auth/[...all]`.
332+
Better Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Next.js to handle all requests sent to `/api/auth/[...all]`.
333333

334-
First, create the necessary directory and file:
334+
In the `src/app/api` directory, create an `auth/[...all]` folder structure and a `route.ts` file inside it:
335335

336336
```terminal
337337
mkdir -p "src/app/api/auth/[...all]"
338338
touch "src/app/api/auth/[...all]/route.ts"
339339
```
340340

341-
Add the following code to the newly created `route.ts` file. This code uses a helper from Better-Auth to create Next.js-compatible `GET` and `POST` request handlers.
341+
Add the following code to the newly created `route.ts` file. This code uses a helper from Better Auth to create Next.js-compatible `GET` and `POST` request handlers.
342342

343343
```ts
344344
import { auth } from "@/lib/auth";
@@ -347,7 +347,7 @@ import { toNextJsHandler } from "better-auth/next-js";
347347
export const { POST, GET } = toNextJsHandler(auth);
348348
```
349349

350-
Next, you'll need a client-side utility to interact with these endpoints from your React components. Create a new file `src/lib/auth-client.ts`:
350+
Next, you'll need a client-side utility to interact with these endpoints from your React components. In the `src/lib` directory, create an `auth-client.ts` file:
351351

352352
```terminal
353353
touch src/lib/auth-client.ts
@@ -363,7 +363,11 @@ export const { signIn, signUp, signOut, useSession } = createAuthClient()
363363

364364
## 5. Set up your pages
365365

366-
Now, let's build the user interface for authentication. Create the pages for signing up, signing in, and a protected dashboard:
366+
Now, let's build the user interface for authentication. In the `src/app` directory, create the following folder structure:
367+
368+
- `sign-up/page.tsx`
369+
- `sign-in/page.tsx`
370+
- `dashboard/page.tsx`
367371

368372
```terminal
369373
mkdir -p src/app/{sign-up,sign-in,dashboard}
@@ -410,7 +414,7 @@ export default function SignUpPage() {
410414
}
411415
```
412416

413-
Now, import the `signUp` function from your Better-Auth client and add the `handleSubmit` function. This function is triggered on form submission and calls the `signUp.email` method provided by Better-Auth, passing the user's name, email, and password.
417+
Now, import the `signUp` function from your Better Auth client and add the `handleSubmit` function. This function is triggered on form submission and calls the `signUp.email` method provided by Better Auth, passing the user's name, email, and password.
414418

415419
```tsx file=src/app/sign-up/page.tsx
416420
"use client";
@@ -611,7 +615,7 @@ export default function SignInPage() {
611615
}
612616
```
613617

614-
Add the `handleSubmit` function, this time importing and using the `signIn.email` method from Better-Auth.
618+
Add the `handleSubmit` function, this time importing and using the `signIn.email` method from Better Auth.
615619

616620
```tsx file=src/app/sign-in/page.tsx
617621
"use client";
@@ -778,7 +782,7 @@ export default function DashboardPage() {
778782
}
779783
```
780784

781-
Import the `useSession` hook from your Better-Auth client. This hook is the key to managing authentication state on the client side. It provides the session data and a pending status.
785+
Import the `useSession` hook from your Better Auth client. This hook is the key to managing authentication state on the client side. It provides the session data and a pending status.
782786

783787
```tsx file=src/app/dashboard/page.tsx
784788
"use client";
@@ -816,7 +820,7 @@ export default function DashboardPage() {
816820
const router = useRouter();
817821
const { data: session, isPending } = useSession();
818822

819-
//add-start: redirect if not signed in
823+
//add-start
820824
useEffect(() => {
821825
if (!isPending && !session?.user) {
822826
router.push("/sign-in");
@@ -851,7 +855,7 @@ export default function DashboardPage() {
851855
}
852856
}, [isPending, session, router]);
853857

854-
//add-start: loading and redirect states
858+
//add-start
855859
if (isPending)
856860
return <p className="text-center mt-8 text-white">Loading...</p>;
857861
if (!session?.user)
@@ -890,7 +894,7 @@ export default function DashboardPage() {
890894
if (!session?.user)
891895
return <p className="text-center mt-8 text-white">Redirecting...</p>;
892896

893-
//add-start: destructure user from session
897+
//add-start
894898
const { user } = session;
895899
//add-end
896900

@@ -899,7 +903,7 @@ export default function DashboardPage() {
899903
<h1 className="text-2xl font-bold">Dashboard</h1>
900904
<p>Welcome, {user.name || "User"}!</p>
901905
<p>Email: {user.email}</p>
902-
{/* add-start: sign out button */}
906+
{/* add-start */}
903907
<button
904908
onClick={() => signOut()}
905909
className="w-full bg-white text-black font-medium rounded-md px-4 py-2 hover:bg-gray-200"
@@ -967,7 +971,7 @@ npx prisma studio
967971

968972
:::success
969973

970-
Congratulations! You now have a fully functional authentication system built with Better-Auth, Prisma, and Next.js.
974+
Congratulations! You now have a fully functional authentication system built with Better Auth, Prisma, and Next.js.
971975

972976
:::
973977

@@ -981,6 +985,6 @@ Congratulations! You now have a fully functional authentication system built wit
981985

982986
## Further reading
983987

984-
- [Better-Auth documentation](https://www.better-auth.com/docs)
988+
- [Better Auth documentation](https://www.better-auth.com/docs)
985989
- [Prisma documentation](/orm/overview/introduction)
986990
- [Next.js App Router](https://nextjs.org/docs/app)

content/800-guides/380-vercel-app-deployment.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Experience the instant deployment flow with [our interactive demo](https://pris.
2323

2424
**Available examples:**
2525
- **Next.js + Prisma**: Basic full-stack application with database integration
26-
- **Next.js + Prisma + Better-Auth**: Complete application with authentication using [Better-Auth](https://www.better-auth.com/)
26+
- **Next.js + Prisma + Better Auth**: Complete application with authentication using [Better Auth](https://www.better-auth.com/)
2727

2828
**Demo features:**
2929

0 commit comments

Comments
 (0)