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"
},
"[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
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

View File

@@ -623,7 +623,7 @@ export const contents: Content[] = [
href: "/docs/integrations/remix",
},
{
title: "Next.js",
title: "Next",
icon: Icons.nextJS,
href: "/docs/integrations/next",
},
@@ -952,9 +952,166 @@ export const contents: Content[] = [
},
],
},
{
title: "Guides",
href: "/docs/guides",
Icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
x="0px"
y="0px"
width="1.8em"
height="1.8em"
fill="currentColor"
viewBox="0 0 100 125"
enableBackground="new 0 0 100 100"
>
<path d="M45.1,77.7L97.9,47l-5.7-3.3L45.1,71.1l-7.9-4.6v0l-29-16.7v-7.7L45,63.4l52.8-30.7L55,7.9L2.1,38.6h0v0l0,0l0,0v14.3h0l0,0 h0v14.3h0l32,18.4v0l11,6.3l52.8-30.7l-5.7-3.3L45.1,85.4l-7.9-4.6v0l-29-16.7v-7.7l26,15v0L45.1,77.7z M39.4,36.4 c1.6-0.8,3.1-1.2,4.4-1.4c1.8-0.2,4.3-0.1,7.6,0.2c1.6,0.2,3.2,0.2,4.7,0c1.5-0.2,2.8-0.7,4-1.3c1.2-0.7,1.9-1.5,2-2.3 c0.1-0.8-0.5-1.6-1.7-2.3c-1-0.6-2.1-0.9-3.4-0.9c-0.8,0-1.6,0.1-2.4,0.3c-0.9,0.3-2.1,0.2-2.9-0.3c0,0,0,0,0,0L47,25.7 c-0.6-0.4-0.6-0.9,0.1-1.2c2.7-1.4,5.6-1.9,8.8-1.7c3.6,0.3,7,1.4,10.3,3.3c3.5,2,5.4,4.2,5.7,6.4c0.3,2.2-1.1,4.2-4.1,5.9 c-1.8,1.1-4.1,1.7-6.8,2c-2.7,0.3-5.3,0.2-7.9-0.3c-1.6-0.2-2.9-0.2-3.9,0.1c-0.7,0.2-1.5,0.4-2.3,0.8c-0.6,0.3-1.6,0.3-2.2-0.1 l-5.2-3C38.7,37.4,38.7,36.8,39.4,36.4z M30.6,41.6l2.7-1.6c0.9-0.5,2.4-0.5,3.3,0l4.2,2.4c0.9,0.5,0.9,1.4,0,1.9l-2.7,1.6 c-0.9,0.5-2.4,0.5-3.3,0l-4.2-2.4C29.7,42.9,29.7,42.1,30.6,41.6z" />
</svg>
),
list: [
{
title: "Auth js (next-auth) Migration Guide",
href: "/docs/guides/next-auth-migration-guide",
icon: () => (
<svg
width="1.7em"
height="1.7em"
viewBox="0 0 24 24"
fill="none"
opacity=".5"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M3.71875 3.92972C5.62789 3.36733 8.45568 2.52411 9.64828 2.16812C10.0173 2.05797 10.4075 2.05711 10.7771 2.16533C11.926 2.50173 14.5984 3.28783 16.6648 3.92349C17.0828 4.05209 17.3679 4.44593 17.3575 4.88319C17.1188 14.9867 12.0196 17.4105 10.5842 17.8936C10.3388 17.9762 10.0837 17.9764 9.83802 17.8945C8.39567 17.4137 3.25421 14.9951 3.00907 4.89714C2.9983 4.45317 3.29276 4.05521 3.71875 3.92972Z"
fill="#D9D9D9"
/>
<mask
id="mask0_156_252"
maskUnits="userSpaceOnUse"
x="3"
y="2"
width="15"
height="16"
>
<path
d="M3.71875 3.92972C5.62789 3.36733 8.45568 2.52411 9.64828 2.16812C10.0173 2.05797 10.4075 2.05711 10.7771 2.16533C11.926 2.50173 14.5984 3.28783 16.6648 3.92349C17.0828 4.05209 17.3679 4.44593 17.3575 4.88319C17.1188 14.9867 12.0196 17.4105 10.5842 17.8936C10.3388 17.9762 10.0837 17.9764 9.83802 17.8945C8.39567 17.4137 3.25421 14.9951 3.00907 4.89714C2.9983 4.45317 3.29276 4.05521 3.71875 3.92972Z"
fill="#D9D9D9"
/>
</mask>
<g mask="url(#mask0_156_252)">
<path
d="M10.2112 9.77465L10.0986 1.71831L17.8169 3.80282L10.2112 9.77465Z"
fill="url(#paint0_linear_156_252)"
/>
<path
d="M10.2113 9.77465V2L2.83098 3.97183L1.81689 8.76056L5.02816 13.7746L10.2113 9.77465Z"
fill="url(#paint1_linear_156_252)"
/>
<path
d="M17.5915 3.97183L4.91547 13.7746V18.2254H17.4225L17.5915 3.97183Z"
fill="url(#paint2_linear_156_252)"
/>
</g>
<defs>
<linearGradient
id="paint0_linear_156_252"
x1="10.2112"
y1="2"
x2="15.6197"
y2="5.5493"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#fff" />
<stop offset="1" stopColor="#fafafa" />
</linearGradient>
<linearGradient
id="paint1_linear_156_252"
x1="3.05633"
y1="4.14085"
x2="10.2113"
y2="9.66197"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#fff" />
<stop offset="1" stopColor="#fafafa" />
</linearGradient>
<linearGradient
id="paint2_linear_156_252"
x1="17.3098"
y1="4.02817"
x2="7.95772"
y2="16.9859"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#4e4e4e" />
<stop offset="1" stopColor="#2e2e2e" />
</linearGradient>
</defs>
</svg>
),
},
],
},
];
export const examples: Content[] = [
{
title: "Examples",
href: "/docs/examples/next",
Icon: () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1.4em"
height="1.4em"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="M2 6.95c0-.883 0-1.324.07-1.692A4 4 0 0 1 5.257 2.07C5.626 2 6.068 2 6.95 2c.386 0 .58 0 .766.017a4 4 0 0 1 2.18.904c.144.119.28.255.554.529L11 4c.816.816 1.224 1.224 1.712 1.495a4 4 0 0 0 .848.352C14.098 6 14.675 6 15.828 6h.374c2.632 0 3.949 0 4.804.77q.119.105.224.224c.77.855.77 2.172.77 4.804V14c0 3.771 0 5.657-1.172 6.828S17.771 22 14 22h-4c-3.771 0-5.657 0-6.828-1.172S2 17.771 2 14z"
opacity=".5"
></path>
<path
fill="currentColor"
d="M20 6.238c0-.298-.005-.475-.025-.63a3 3 0 0 0-2.583-2.582C17.197 3 16.965 3 16.5 3H9.988c.116.104.247.234.462.45L11 4c.816.816 1.224 1.224 1.712 1.495a4 4 0 0 0 .849.352C14.098 6 14.675 6 15.829 6h.373c1.78 0 2.957 0 3.798.238"
></path>
<path
fill="currentColor"
fillRule="evenodd"
d="M12.25 10a.75.75 0 0 1 .75-.75h5a.75.75 0 0 1 0 1.5h-5a.75.75 0 0 1-.75-.75"
clipRule="evenodd"
></path>
</svg>
),
list: [
{
title: "Astro + SolidJs",
href: "/docs/examples/astro",
icon: Icons.astro,
},
{
title: "Remix",
href: "/docs/examples/remix",
icon: Icons.remix,
},
{
title: "Next JS",
href: "/docs/examples/next-js",
icon: Icons.nextJS,
},
{
title: "Nuxt",
href: "/docs/examples/nuxt",
icon: Icons.nuxt,
},
{
title: "Svelte Kit",
href: "/docs/examples/svelte-kit",
icon: Icons.svelteKit,
},
],
},
{
title: "Examples",
href: "/docs/examples/next",

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
*/
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
*/