docs: add next-auth migration guide (#584)

This commit is contained in:
Mohammed Ibrahim
2024-11-19 22:25:14 +03:00
committed by GitHub
parent f5f60a23e8
commit b810f55851
5 changed files with 1049 additions and 708 deletions

View File

@@ -21,6 +21,6 @@
"editor.defaultFormatter": "biomejs.biome" "editor.defaultFormatter": "biomejs.biome"
}, },
"[typescriptreact]": { "[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome" "editor.defaultFormatter": "esbenp.prettier-vscode"
} }
} }

View File

@@ -42,10 +42,12 @@ If you see any security issue we prefer you to disclose it via an email (securit
1. Fork the repo 1. Fork the repo
2. clone your fork. 2. clone your fork.
3. install node.js (preferable latest LTS). 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. 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. 6. build the project using `pnpm build`
7. implement your changes. 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 ## Testing

File diff suppressed because it is too large Load Diff

View 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, well 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 youre 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 Auths 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! Youve 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.

View File

@@ -13,7 +13,15 @@ export const accountSchema = z.object({
/** /**
* Access token expires at * 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 * Password is only stored in the credential provider
*/ */