mirror of
https://github.com/LukeHagar/better-auth.git
synced 2025-12-06 12:27:44 +00:00
docs: add next-auth migration guide (#584)
This commit is contained in:
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -21,6 +21,6 @@
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +42,12 @@ If you see any security issue we prefer you to disclose it via an email (securit
|
||||
1. Fork the repo
|
||||
2. clone your fork.
|
||||
3. install node.js (preferable latest LTS).
|
||||
4. run pnpm i in your terminal to install dependencies.
|
||||
4. run `pnpm i` in your terminal to install dependencies.
|
||||
5. create a branch.
|
||||
6. create a draft pull request. link the relevant issue by referring to it in the PR's description. Eg.closes #123 will link the PR to issue/pull request #123.
|
||||
7. implement your changes.
|
||||
6. build the project using `pnpm build`
|
||||
7. run `pnpm -F docs` dev (to run the docs section)
|
||||
8. create a draft pull request. link the relevant issue by referring to it in the PR's description. Eg.closes #123 will link the PR to issue/pull request #123.
|
||||
9. implement your changes.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
174
docs/content/docs/guides/next-auth-migration-guide.mdx
Normal file
174
docs/content/docs/guides/next-auth-migration-guide.mdx
Normal file
@@ -0,0 +1,174 @@
|
||||
---
|
||||
title: Migrating from NextAuth to BetterAuth
|
||||
description: A step-by-step guide to getting started with BetterAuth.
|
||||
---
|
||||
|
||||
In this guide, we’ll explore how to seamlessly transition a project from Next Auth to Better Auth while ensuring that no data or functionality is lost. This guide assumes you’re using Next.js as your framework, but it should be applicable to other frameworks as well.
|
||||
|
||||
## Before we get started
|
||||
|
||||
Before we start the migration process, we need to setup BetterAuth in our project. You can use the [installation guide](/docs/guides/installation) to get started.
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
### Mapping Existing Columns
|
||||
|
||||
Rather than replacing existing column names in your database, you can map them to Better Auth’s expected structure. This way, you can maintain your existing database schema.
|
||||
|
||||
|
||||
#### User Schema
|
||||
|
||||
Next Auth default uesr schema is the same as what is expected by Better Auth so there shouldn't be any problem there.
|
||||
|
||||
#### Session Schema
|
||||
|
||||
We need to map 2 fields in the session schema:
|
||||
|
||||
- expires to expiresAt
|
||||
- sessionToken to token
|
||||
|
||||
```ts title="auth.ts"
|
||||
export const auth = betterAuth({
|
||||
//...Other configs
|
||||
session: {
|
||||
fields: {
|
||||
expiresAt: "expires", // or "expires_at" or whatever your existing field is
|
||||
token: "sessionToken" // or "session_token" or whatever your existing field is
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Accounts Schema
|
||||
|
||||
We need to map some fields in the accounts schema.
|
||||
|
||||
- providerAccountId to accountId
|
||||
- refersh_token to refreshToken
|
||||
- access_token to accessToken
|
||||
- access_token_expires to accessTokenExpiresAt
|
||||
- id_token to idToken
|
||||
|
||||
and you can remove "session_state", "type" and "token_type" fields as they are not needed by Better Auth.
|
||||
|
||||
|
||||
```ts title="auth.ts"
|
||||
export const auth = betterAuth({
|
||||
// Other configs
|
||||
accounts: {
|
||||
fields: {
|
||||
accountId: "providerAccountId",
|
||||
refreshToken: "refresh_token",
|
||||
accessToken: "access_token",
|
||||
accessTokenExpiresAt: "access_token_expires",
|
||||
idToken: "id_token",
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**NOTE:** If you're using orm adapters, you can also map the fields in the adapter like
|
||||
|
||||
**Example with Prisma**
|
||||
```prisma title="schema.prisma"
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
expires DateTime @map("expiresAt") // Map expires to your existing expires field // [!code highlight]
|
||||
token String @@map("sessionToken") // Map token to your existing sessionToken field // [!code highlight]
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
## Change Route Handler
|
||||
|
||||
If you haven't noticed this in the installation guide, navigate to the `app/api/auth` folder and rename the `[...nextauth]` file to `[...all]` to avoid confusion. Inside the `route.ts` file, add the following code:
|
||||
|
||||
```typescript title="app/api/auth/[...all]/route.ts"
|
||||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
import { auth } from "~/server/auth";
|
||||
|
||||
export const { POST, GET } = toNextJsHandler(auth);
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Client
|
||||
|
||||
Next, create a file named `auth-client.ts` in the `lib` folder. Add the following code to the file:
|
||||
|
||||
```typescript
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.BASE_URL! // Your API base URL (optional if it's the same as the frontend)
|
||||
})
|
||||
export const { signIn, signOut, useSession } = authClient;
|
||||
```
|
||||
|
||||
### Add your social login functions
|
||||
|
||||
change your signIn functions from NextAuth to Better Auth. Here is an example of how to do that for discord:
|
||||
|
||||
```typescript
|
||||
import { signIn } from "~/lib/auth-client"
|
||||
|
||||
export const signInDiscord = async () => {
|
||||
const data = await signIn.social({
|
||||
provider: "discord"
|
||||
})
|
||||
return data
|
||||
}
|
||||
```
|
||||
|
||||
### Change `useSession` calls
|
||||
|
||||
Change your `useSession` calls from NextAuth to Better Auth. Here is an example of how to do that:
|
||||
|
||||
```tsx title="Profile.tsx"
|
||||
import { useSession } from "~/lib/auth-client"
|
||||
|
||||
export const Profile = () => {
|
||||
const { data } = useSession()
|
||||
return (
|
||||
<div>
|
||||
<pre>
|
||||
{JSON.stringify(data, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
### Get Server Session
|
||||
|
||||
To get session data on the server, you can use the auth instance you created in the `auth.ts` file. Here is an example of how to do that:
|
||||
|
||||
```typescript title="actions.ts"
|
||||
"use server";
|
||||
|
||||
import { auth } from "~/lib/auth";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export const protectedAction = ()=>{
|
||||
const session = auth.api.getSession({
|
||||
headers: await headers();
|
||||
})
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Middleware
|
||||
|
||||
To protect routes with middleware see [next middleware guide](/docs/integrations/next#middleware).
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Wrapping up
|
||||
|
||||
Congratulations! You’ve successfully migrated from NextAuth to BetterAuth. If you'd like to see a more complete code or a live demo, check out the full implementation with multiple auth added [here](https://github.com/Bekacru/t3-app-better-auth).
|
||||
|
||||
Better Auth provides a lot more features and flexibility, so be sure to explore our docs to see what else you can do with it.
|
||||
@@ -13,7 +13,15 @@ export const accountSchema = z.object({
|
||||
/**
|
||||
* Access token expires at
|
||||
*/
|
||||
expiresAt: z.date().nullish(),
|
||||
accessTokenExpiresAt: z.date().nullish(),
|
||||
/**
|
||||
* Refresh token expires at
|
||||
*/
|
||||
refreshTokenExpiresAt: z.date().nullish(),
|
||||
/**
|
||||
* The scopes that the user has authorized
|
||||
*/
|
||||
scope: z.string().nullish(),
|
||||
/**
|
||||
* Password is only stored in the credential provider
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user