mirror of
https://github.com/SrIzan10/next-auth.git
synced 2026-05-01 10:55:20 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16a2e37fd6 | ||
|
|
0392a8df9a | ||
|
|
a459b95c5b | ||
|
|
13df7eb81d | ||
|
|
62f261209c | ||
|
|
da43d0d896 | ||
|
|
4b1271ba75 | ||
|
|
d30da0170f | ||
|
|
887b2985fc | ||
|
|
d2bbac1164 |
@@ -4,7 +4,7 @@
|
||||
NEXTAUTH_URL=http://localhost:3000
|
||||
|
||||
# You can use `openssl rand -hex 32` or
|
||||
# https://generate-secret.now.sh/32 to generate a secret.
|
||||
# https://generate-secret.vercel.app/32 to generate a secret.
|
||||
# Note: Changing a secret may invalidate existing sessions
|
||||
# and/or verificaion tokens.
|
||||
SECRET=
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
export default function WorkOS(options) {
|
||||
const domain = options.domain || 'api.workos.com';
|
||||
|
||||
return {
|
||||
id: 'workos',
|
||||
name: 'WorkOS',
|
||||
@@ -10,9 +12,9 @@ export default function WorkOS(options) {
|
||||
client_id: options.clientId,
|
||||
client_secret: options.clientSecret
|
||||
},
|
||||
accessTokenUrl: 'https://api.workos.com/sso/token/',
|
||||
authorizationUrl: `https://api.workos.com/sso/authorize/?response_type=code&domain=${options.domain}`,
|
||||
profileUrl: 'https://api.workos.com/sso/profile/',
|
||||
accessTokenUrl: `https://${domain}/sso/token`,
|
||||
authorizationUrl: `https://${domain}/sso/authorize?response_type=code`,
|
||||
profileUrl: `https://${domain}/sso/profile`,
|
||||
profile: (profile) => {
|
||||
return {
|
||||
...profile,
|
||||
|
||||
@@ -15,9 +15,9 @@ export default async function getAuthorizationUrl (req) {
|
||||
if (provider.version?.startsWith('2.')) {
|
||||
// Handle OAuth v2.x
|
||||
let url = client.getAuthorizeUrl({
|
||||
scope: provider.scope,
|
||||
...params,
|
||||
redirect_uri: provider.callbackUrl,
|
||||
scope: provider.scope
|
||||
redirect_uri: provider.callbackUrl
|
||||
})
|
||||
|
||||
// If the authorizationUrl specified in the config has query parameters on it
|
||||
|
||||
71
www/docs/adapters/dynamodb.md
Normal file
71
www/docs/adapters/dynamodb.md
Normal file
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: dynamodb
|
||||
title: DynamoDB Adapter
|
||||
---
|
||||
|
||||
# DynamoDB
|
||||
|
||||
This is the AWS DynamoDB Adapter for next-auth. This package can only be used in conjunction with the primary next-auth package. It is not a standalone package.
|
||||
|
||||
You need a table with a partition key `pk` and a sort key `sk`. Your table also needs a global secondary index named `GSI1` with `GSI1PK` as partition key and `GSI1SK` as sorting key. You can set whatever you want as the table name and the billing method.
|
||||
|
||||
You can find the full schema in the table structure section below.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install `next-auth` and `@next-auth/dynamodb-adapter`
|
||||
|
||||
```js
|
||||
npm install next-auth @next-auth/dynamodb-adapter
|
||||
```
|
||||
|
||||
2. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
|
||||
|
||||
You need to pass `aws-sdk` to the adapter in addition to the table name.
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
import AWS from "aws-sdk";
|
||||
import NextAuth from "next-auth";
|
||||
import Providers from "next-auth/providers";
|
||||
import { DynamoDBAdapter } from "@next-auth/dynamodb-adapter"
|
||||
|
||||
AWS.config.update({
|
||||
accessKeyId: process.env.NEXT_AUTH_AWS_ACCESS_KEY,
|
||||
secretAccessKey: process.env.NEXT_AUTH_AWS_SECRET_KEY,
|
||||
region: process.env.NEXT_AUTH_AWS_REGION,
|
||||
});
|
||||
|
||||
export default NextAuth({
|
||||
// Configure one or more authentication providers
|
||||
providers: [
|
||||
Providers.GitHub({
|
||||
clientId: process.env.GITHUB_ID,
|
||||
clientSecret: process.env.GITHUB_SECRET,
|
||||
}),
|
||||
Providers.Email({
|
||||
server: process.env.EMAIL_SERVER,
|
||||
from: process.env.EMAIL_FROM,
|
||||
}),
|
||||
// ...add more providers here
|
||||
],
|
||||
adapter: DynamoDBAdapter({
|
||||
AWS,
|
||||
tableName: "next-auth-test",
|
||||
}),
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
(AWS secrets start with `NEXT_AUTH_` in order to not conflict with [Vercel's reserved environment variables](https://vercel.com/docs/environment-variables#reserved-environment-variables).)
|
||||
|
||||
## Schema
|
||||
|
||||
The table respects the single table design pattern. This has many advantages:
|
||||
|
||||
- Only one table to manage, monitor and provision.
|
||||
- Querying relations is faster than with multi-table schemas (for eg. retreiving all sessions for a user).
|
||||
- Only one table needs to be replicated, if you want to go multi-region.
|
||||
|
||||
Here is a schema of the table :
|
||||
|
||||

|
||||
84
www/docs/adapters/fauna.md
Normal file
84
www/docs/adapters/fauna.md
Normal file
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: fauna
|
||||
title: FaunaDB Adapter
|
||||
---
|
||||
|
||||
# FaunaDB
|
||||
|
||||
This is the Fauna Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
|
||||
|
||||
You can find the Fauna schema and seed information in the docs at [next-auth.js.org/adapters/fauna](https://next-auth.js.org/adapters/fauna).
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install `next-auth` and `@next-auth/fauna-adapter`
|
||||
|
||||
```js
|
||||
npm install next-auth @next-auth/fauna-adapter
|
||||
```
|
||||
|
||||
2. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
import NextAuth from "next-auth"
|
||||
import Providers from "next-auth/providers"
|
||||
import * as Fauna from "faunadb"
|
||||
import { FaunaAdapter } from "@next-auth/fauna-adapter"
|
||||
|
||||
const client = new Fauna.Client({
|
||||
secret: "secret",
|
||||
scheme: "http",
|
||||
domain: "localhost",
|
||||
port: 8443,
|
||||
})
|
||||
|
||||
// For more information on each option (and a full list of options) go to
|
||||
// https://next-auth.js.org/configuration/options
|
||||
export default NextAuth({
|
||||
// https://next-auth.js.org/configuration/providers
|
||||
providers: [
|
||||
Providers.Google({
|
||||
clientId: process.env.GOOGLE_ID,
|
||||
clientSecret: process.env.GOOGLE_SECRET,
|
||||
}),
|
||||
],
|
||||
adapter: FaunaAdapter({ faunaClient: client})
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
## Schema
|
||||
|
||||
```javascript
|
||||
CreateCollection({ name: "accounts" })
|
||||
CreateCollection({ name: "sessions" })
|
||||
CreateCollection({ name: "users" })
|
||||
CreateCollection({ name: "verification_requests" })
|
||||
CreateIndex({
|
||||
name: "account_by_provider_account_id",
|
||||
source: Collection("accounts"),
|
||||
unique: true,
|
||||
terms: [
|
||||
{ field: ["data", "providerId"] },
|
||||
{ field: ["data", "providerAccountId"] },
|
||||
],
|
||||
})
|
||||
CreateIndex({
|
||||
name: "session_by_token",
|
||||
source: Collection("sessions"),
|
||||
unique: true,
|
||||
terms: [{ field: ["data", "sessionToken"] }],
|
||||
})
|
||||
CreateIndex({
|
||||
name: "user_by_email",
|
||||
source: Collection("users"),
|
||||
unique: true,
|
||||
terms: [{ field: ["data", "email"] }],
|
||||
})
|
||||
CreateIndex({
|
||||
name: "verification_request_by_token",
|
||||
source: Collection("verification_requests"),
|
||||
unique: true,
|
||||
terms: [{ field: ["data", "token"] }, { field: ["data", "identifier"] }],
|
||||
})
|
||||
```
|
||||
40
www/docs/adapters/firebase.md
Normal file
40
www/docs/adapters/firebase.md
Normal file
@@ -0,0 +1,40 @@
|
||||
---
|
||||
id: firebase
|
||||
title: Firebase Adapter
|
||||
---
|
||||
|
||||
# Firebase
|
||||
|
||||
This is the Firebase Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install `next-auth` and `@next-auth/firebase-adapter`
|
||||
|
||||
```js
|
||||
npm install next-auth @next-auth/firebase-adapter
|
||||
```
|
||||
|
||||
2. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
import NextAuth from "next-auth"
|
||||
import Providers from "next-auth/providers"
|
||||
import { FirebaseAdapter } from "@next-auth/firebase-adapter"
|
||||
import firebase from "firebase-admin"
|
||||
const firestore = firebase.initializeApp({ /* your config */ }).firestore()
|
||||
|
||||
// For more information on each option (and a full list of options) go to
|
||||
// https://next-auth.js.org/configuration/options
|
||||
export default NextAuth({
|
||||
// https://next-auth.js.org/configuration/providers
|
||||
providers: [
|
||||
Providers.Google({
|
||||
clientId: process.env.GOOGLE_ID,
|
||||
clientSecret: process.env.GOOGLE_SECRET,
|
||||
}),
|
||||
],
|
||||
adapter: FirebaseAdapter(firestore),
|
||||
...
|
||||
})
|
||||
```
|
||||
42
www/docs/adapters/overview.md
Normal file
42
www/docs/adapters/overview.md
Normal file
@@ -0,0 +1,42 @@
|
||||
---
|
||||
id: overview
|
||||
title: Overview
|
||||
---
|
||||
|
||||
An **Adapter** in NextAuth.js connects your application to whatever database or backend system you want to use to store data for user accounts, sessions, etc.
|
||||
|
||||
The adapters can be found in their own repository under [`nextauthjs/adapters`](https://github.com/nextauthjs/adapters).
|
||||
|
||||
There you can find the following adapters:
|
||||
|
||||
- [`typeorm-legacy`](./typeorm/typeorm-overview)
|
||||
- [`prisma`](./prisma)
|
||||
- [`prisma-legacy`](./prisma)
|
||||
- [`fauna`](./fauna)
|
||||
- [`dynamodb`](./dynamodb)
|
||||
- [`firebase`](./firebase)
|
||||
|
||||
## Custom Adapter
|
||||
|
||||
See the tutorial for [creating a database Adapter](/tutorials/creating-a-database-adapter) for more information on how to create a custom Adapter. Have a look at the [Adapter repository](https://github.com/nextauthjs/adapters) to see community maintained custom Adapter or add your own.
|
||||
|
||||
### Editor integration
|
||||
|
||||
When writing your own custom Adapter in plain JavaScript, note that you can use **JSDoc** to get helpful editor hints and auto-completion like so:
|
||||
|
||||
```js
|
||||
/** @type { import("next-auth/adapters").Adapter } */
|
||||
const MyAdapter = () => {
|
||||
return {
|
||||
async getAdapter() {
|
||||
return {
|
||||
// your adapter methods here
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
This will work in code editors with a strong TypeScript integration like VSCode or WebStorm. It might not work if you're using more lightweight editors like VIM or Atom.
|
||||
:::
|
||||
258
www/docs/adapters/prisma.md
Normal file
258
www/docs/adapters/prisma.md
Normal file
@@ -0,0 +1,258 @@
|
||||
---
|
||||
id: prisma
|
||||
title: Prisma Adapter
|
||||
---
|
||||
|
||||
# Prisma
|
||||
|
||||
You can also use NextAuth.js with the experimental Adapter for [Prisma](https://www.prisma.io/docs/).
|
||||
|
||||
:::info
|
||||
You may have noticed there is a `prisma` and `prisma-legacy` adapter. This is due to legacy reasons, but the code has mostly converged so that there is no longer much difference between the two. The legacy adapter does have one feature that the newer one does not, and that is the ability to rename tables.
|
||||
:::
|
||||
|
||||
To use this Adapter, you need to install Prisma Client and Prisma CLI:
|
||||
|
||||
```
|
||||
npm install @prisma/client @next-auth/prisma-adapter
|
||||
npm install prisma --save-dev
|
||||
```
|
||||
|
||||
Configure your NextAuth.js to use the Prisma Adapter:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
import NextAuth from "next-auth"
|
||||
import Providers from "next-auth/providers"
|
||||
import { PrismaAdapter } from "@next-auth/prisma-adapter"
|
||||
import { PrismaClient } from "@prisma/client"
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export default NextAuth({
|
||||
providers: [
|
||||
Providers.Google({
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
}),
|
||||
],
|
||||
adapter: PrismaAdapter({ prisma }),
|
||||
})
|
||||
```
|
||||
|
||||
:::tip
|
||||
While Prisma includes an experimental feature in the migration command that is able to generate SQL from a schema, creating tables and columns using the provided SQL is currently recommended instead as SQL schemas automatically generated by Prisma may differ from the recommended schemas.
|
||||
:::
|
||||
Schema for the Prisma Adapter (`@next-auth/prisma-adapter`)
|
||||
|
||||
## Setup
|
||||
|
||||
Create a schema file in `prisma/schema.prisma` similar to this one:
|
||||
|
||||
```json title="schema.prisma"
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./dev.db"
|
||||
}
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
providerType String
|
||||
providerId String
|
||||
providerAccountId String
|
||||
refreshToken String?
|
||||
accessToken String?
|
||||
accessTokenExpires DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
|
||||
@@unique([providerId, providerAccountId])
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
expires DateTime
|
||||
sessionToken String @unique
|
||||
accessToken String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
name String?
|
||||
email String? @unique
|
||||
emailVerified DateTime?
|
||||
image String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
}
|
||||
|
||||
model VerificationRequest {
|
||||
id String @id @default(cuid())
|
||||
identifier String
|
||||
token String @unique
|
||||
expires DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([identifier, token])
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Generate Client
|
||||
|
||||
Once you have saved your schema, use the Prisma CLI to generate the Prisma Client:
|
||||
|
||||
```
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
To configure you database to use the new schema (i.e. create tables and columns) use the `prisma migrate` command:
|
||||
|
||||
```
|
||||
npx prisma migrate dev
|
||||
```
|
||||
|
||||
To generate a schema in this way with the above example code, you will need to specify your datbase connection string in the environment variable `DATABASE_URL`. You can do this by setting it in a `.env` file at the root of your project.
|
||||
|
||||
As this feature is experimental in Prisma, it is behind a feature flag. You should check your database schema manually after using this option. See the [Prisma documentation](https://www.prisma.io/docs/) for information on how to use `prisma migrate`.
|
||||
|
||||
### Custom Models
|
||||
|
||||
You can add properties to the schema and map them to any database column names you wish, but you should not change the base properties or types defined in the example schema.
|
||||
|
||||
The model names themselves can be changed with a configuration option, and the datasource can be changed to anything supported by Prisma.
|
||||
|
||||
You can use custom model names by using the `modelMapping` option (shown here with default values).
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
adapter: PrismaAdapter({
|
||||
prisma,
|
||||
modelMapping: {
|
||||
User: 'user',
|
||||
Account: 'account',
|
||||
Session: 'session',
|
||||
VerificationRequest: 'verificationRequest'
|
||||
}
|
||||
})
|
||||
...
|
||||
```
|
||||
|
||||
:::tip
|
||||
If you experience issues with Prisma opening too many database connections in local development mode (e.g. due to Hot Module Reloading) you can use an approach like this when initalising the Prisma Client:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
let prisma
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
prisma = new PrismaClient()
|
||||
} else {
|
||||
if (!global.prisma) {
|
||||
global.prisma = new PrismaClient()
|
||||
}
|
||||
prisma = global.prisma
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Schema History
|
||||
|
||||
Changes from the original Prisma Adapter
|
||||
|
||||
```diff
|
||||
model Account {
|
||||
- id Int @default(autoincrement()) @id
|
||||
+ id String @id @default(cuid())
|
||||
- compoundId String @unique @map(name: "compound_id")
|
||||
- userId Int @map(name: "user_id")
|
||||
+ userId String
|
||||
+ user User @relation(fields: [userId], references: [id])
|
||||
- providerType String @map(name: "provider_type")
|
||||
+ providerType String
|
||||
- providerId String @map(name: "provider_id")
|
||||
+ providerId String
|
||||
- providerAccountId String @map(name: "provider_account_id")
|
||||
+ providerAccountId String
|
||||
- refreshToken String? @map(name: "refresh_token")
|
||||
+ refreshToken String?
|
||||
- accessToken String? @map(name: "access_token")
|
||||
+ accessToken String?
|
||||
- accessTokenExpires DateTime? @map(name: "access_token_expires")
|
||||
+ accessTokenExpires DateTime?
|
||||
- createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
+ createdAt DateTime @default(now())
|
||||
- updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
+ updatedAt DateTime @updatedAt
|
||||
|
||||
- @@index([providerAccountId], name: "providerAccountId")
|
||||
- @@index([providerId], name: "providerId")
|
||||
- @@index([userId], name: "userId")
|
||||
- @@map(name: "accounts")
|
||||
+ @@unique([providerId, providerAccountId])
|
||||
}
|
||||
|
||||
model Session {
|
||||
- id Int @default(autoincrement()) @id
|
||||
+ id String @id @default(cuid())
|
||||
- userId Int @map(name: "user_id")
|
||||
+ userId String
|
||||
+ user User @relation(fields: [userId], references: [id])
|
||||
expires DateTime
|
||||
- sessionToken String @unique @map(name: "session_token")
|
||||
+ sessionToken String @unique
|
||||
- accessToken String @unique @map(name: "access_token")
|
||||
+ accessToken String @unique
|
||||
- createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
+ createdAt DateTime @default(now())
|
||||
- updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
+ updatedAt DateTime @updatedAt
|
||||
-
|
||||
- @@map(name: "sessions")
|
||||
}
|
||||
|
||||
model User {
|
||||
- id Int @default(autoincrement()) @id
|
||||
+ id String @id @default(cuid())
|
||||
name String?
|
||||
email String? @unique
|
||||
- emailVerified DateTime? @map(name: "email_verified")
|
||||
+ emailVerified DateTime?
|
||||
image String?
|
||||
+ accounts Account[]
|
||||
+ sessions Session[]
|
||||
- createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
+ createdAt DateTime @default(now())
|
||||
- updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
+ updatedAt DateTime @updatedAt
|
||||
|
||||
- @@map(name: "users")
|
||||
}
|
||||
|
||||
model VerificationRequest {
|
||||
- id Int @default(autoincrement()) @id
|
||||
+ id String @id @default(cuid())
|
||||
identifier String
|
||||
token String @unique
|
||||
expires DateTime
|
||||
- createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
+ createdAt DateTime @default(now())
|
||||
- updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
+ updatedAt DateTime @updatedAt
|
||||
|
||||
- @@map(name: "verification_requests")
|
||||
+ @@unique([identifier, token])
|
||||
}
|
||||
```
|
||||
49
www/docs/adapters/typeorm/overview.md
Normal file
49
www/docs/adapters/typeorm/overview.md
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
id: typeorm-overview
|
||||
title: Overview
|
||||
---
|
||||
|
||||
## TypeORM Adapter
|
||||
|
||||
NextAuth.js comes with a default Adapter that uses [TypeORM](https://typeorm.io/) so that it can be used with many different databases without any further configuration, you simply add the node module for the database driver you want to use in your project and pass a database connection string to NextAuth.js.
|
||||
|
||||
### Database Schemas
|
||||
|
||||
Configure your database by creating the tables and columns to match the schema expected by NextAuth.js.
|
||||
|
||||
- [MySQL Schema](./mysql)
|
||||
- [Postgres Schema](./postgres)
|
||||
- [Microsoft SQL Server Schema](./mssql)
|
||||
- [MongoDB](./mongodb)
|
||||
|
||||
The default Adapter is the TypeORM Adapter and the default database type for TypeORM is SQLite, the following configuration options are exactly equivalent.
|
||||
|
||||
```javascript
|
||||
database: {
|
||||
type: 'sqlite',
|
||||
database: ':memory:',
|
||||
synchronize: true
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
adapter: Adapters.Default({
|
||||
type: "sqlite",
|
||||
database: ":memory:",
|
||||
synchronize: true,
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
adapter: Adapters.TypeORM.Adapter({
|
||||
type: "sqlite",
|
||||
database: ":memory:",
|
||||
synchronize: true,
|
||||
})
|
||||
```
|
||||
|
||||
The tutorial [Custom models with TypeORM](/tutorials/typeorm-custom-models) explains how to extend the built in models and schemas used by the TypeORM Adapter. You can use these models in your own code.
|
||||
|
||||
:::tip
|
||||
The `synchronize` option in TypeORM will generate SQL that exactly matches the documented schemas for MySQL and Postgres. This will automatically apply any changes it finds in the entity model, therefore it **should not be enabled against production databases** as it may cause data loss if the configured schema does not match the expected schema!
|
||||
:::
|
||||
@@ -78,11 +78,6 @@ When using NextAuth.js with a database, the User object will be either a user ob
|
||||
When using NextAuth.js without a database, the user object it will always be a prototype user object, with information extracted from the profile.
|
||||
:::
|
||||
|
||||
:::tip
|
||||
If you only want to allow users who already have accounts in the database to sign in, you can check for the existence of a `user.id` property and reject any sign in attempts from accounts that do not have one.
|
||||
|
||||
If you are using NextAuth.js without database and want to control who can sign in, you can check their email address or profile against a hard coded list in the `signIn()` callback.
|
||||
:::
|
||||
|
||||
## Redirect callback
|
||||
|
||||
|
||||
@@ -5,16 +5,20 @@ title: Databases
|
||||
|
||||
NextAuth.js comes with multiple ways of connecting to a database:
|
||||
|
||||
* **TypeORM** (default)<br/>
|
||||
_The TypeORM adapter supports MySQL, Postgres, MsSql, SQLite and MongoDB databases._
|
||||
* **Prisma**<br/>
|
||||
_The Prisma 2 adapter supports MySQL, Postgres and SQLite databases._
|
||||
* **Custom Adapter**<br/>
|
||||
- **TypeORM** (default)<br/>
|
||||
_The TypeORM adapter supports MySQL, PostgreSQL, MSSQL, SQLite and MongoDB databases._
|
||||
- **Prisma**<br/>
|
||||
_The Prisma 2 adapter supports MySQL, PostgreSQL and SQLite databases._
|
||||
- **Fauna**<br/>
|
||||
_The FaunaDB adapter only supports FaunaDB._
|
||||
- **Custom Adapter**<br/>
|
||||
_A custom Adapter can be used to connect to any database._
|
||||
|
||||
> There are currently efforts in the [`nextauthjs/adapters`](https://github.com/nextauthjs/adapters) repository to get community-based DynamoDB, Sanity, PouchDB and Sequelize Adapters merged. If you are interested in any of the above, feel free to check out the PRs in the `nextauthjs/adapters` repository!
|
||||
|
||||
**This document covers the default adapter (TypeORM).**
|
||||
|
||||
See the [documentation for adapters](/schemas/adapters) to learn more about using Prisma adapter or using a custom adapter.
|
||||
See the [documentation for adapters](/adapters/overview) to learn more about using Prisma adapter or using a custom adapter.
|
||||
|
||||
To learn more about databases in NextAuth.js and how they are used, check out [databases in the FAQ](/faq#databases).
|
||||
|
||||
@@ -27,7 +31,7 @@ You can specify database credentials as as a connection string or a [TypeORM con
|
||||
The following approaches are exactly equivalent:
|
||||
|
||||
```js
|
||||
database: 'mysql://nextauth:password@127.0.0.1:3306/database_name'
|
||||
database: "mysql://nextauth:password@127.0.0.1:3306/database_name"
|
||||
```
|
||||
|
||||
```js
|
||||
@@ -44,13 +48,14 @@ database: {
|
||||
:::tip
|
||||
You can pass in any valid [TypeORM configuration option](https://github.com/typeorm/typeorm/blob/master/docs/using-ormconfig.md).
|
||||
|
||||
*e.g. To set a prefix for all table names you can use the **entityPrefix** option as connection string parameter:*
|
||||
_e.g. To set a prefix for all table names you can use the **entityPrefix** option as connection string parameter:_
|
||||
|
||||
```js
|
||||
'mysql://nextauth:password@127.0.0.1:3306/database_name?entityPrefix=nextauth_'
|
||||
"mysql://nextauth:password@127.0.0.1:3306/database_name?entityPrefix=nextauth_"
|
||||
|
||||
```
|
||||
|
||||
*…or as a database configuration object:*
|
||||
_…or as a database configuration object:_
|
||||
|
||||
```js
|
||||
database: {
|
||||
@@ -63,6 +68,7 @@ database: {
|
||||
entityPrefix: 'nextauth_'
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
---
|
||||
@@ -73,15 +79,15 @@ Using SQL to create tables and columns is the recommended way to set up an SQL d
|
||||
|
||||
Check out the links below for SQL you can run to set up a database for NextAuth.js.
|
||||
|
||||
* [MySQL Schema](/schemas/mysql)
|
||||
* [Postgres Schema](/schemas/postgres)
|
||||
- [MySQL Schema](/adapters/typeorm/mysql)
|
||||
- [Postgres Schema](/adapters/typeorm/postgres)
|
||||
|
||||
_If you are running SQLite, MongoDB or a Document database you can skip this step._
|
||||
|
||||
Alternatively, you can also have your database configured automatically using the `synchronize: true` option:
|
||||
|
||||
```js
|
||||
database: 'mysql://nextauth:password@127.0.0.1:3306/database_name?synchronize=true'
|
||||
database: "mysql://nextauth:password@127.0.0.1:3306/database_name?synchronize=true"
|
||||
```
|
||||
|
||||
```js
|
||||
@@ -122,7 +128,7 @@ Install module:
|
||||
#### Example
|
||||
|
||||
```js
|
||||
database: 'mysql://username:password@127.0.0.1:3306/database_name'
|
||||
database: "mysql://username:password@127.0.0.1:3306/database_name"
|
||||
```
|
||||
|
||||
### MariaDB
|
||||
@@ -133,7 +139,7 @@ Install module:
|
||||
#### Example
|
||||
|
||||
```js
|
||||
database: 'mariadb://username:password@127.0.0.1:3306/database_name'
|
||||
database: "mariadb://username:password@127.0.0.1:3306/database_name"
|
||||
```
|
||||
|
||||
### Postgres / CockroachDB
|
||||
@@ -144,13 +150,15 @@ Install module:
|
||||
#### Example
|
||||
|
||||
PostgresDB
|
||||
|
||||
```js
|
||||
database: 'postgres://username:password@127.0.0.1:5432/database_name'
|
||||
database: "postgres://username:password@127.0.0.1:5432/database_name"
|
||||
```
|
||||
|
||||
CockroachDB
|
||||
|
||||
```js
|
||||
database: 'postgres://username:password@127.0.0.1:26257/database_name'
|
||||
database: "postgres://username:password@127.0.0.1:26257/database_name"
|
||||
```
|
||||
|
||||
If the node is using Self-signed cert
|
||||
@@ -182,7 +190,7 @@ Install module:
|
||||
#### Example
|
||||
|
||||
```js
|
||||
database: 'mssql://sa:password@localhost:1433/database_name'
|
||||
database: "mssql://sa:password@localhost:1433/database_name"
|
||||
```
|
||||
|
||||
### MongoDB
|
||||
@@ -193,12 +201,12 @@ Install module:
|
||||
#### Example
|
||||
|
||||
```js
|
||||
database: 'mongodb://username:password@127.0.0.1:3306/database_name'
|
||||
database: "mongodb://username:password@127.0.0.1:3306/database_name"
|
||||
```
|
||||
|
||||
### SQLite
|
||||
|
||||
*SQLite is intended only for development / testing and not for production use.*
|
||||
_SQLite is intended only for development / testing and not for production use._
|
||||
|
||||
Install module:
|
||||
`npm i sqlite3`
|
||||
@@ -206,9 +214,9 @@ Install module:
|
||||
#### Example
|
||||
|
||||
```js
|
||||
database: 'sqlite://localhost/:memory:'
|
||||
database: "sqlite://localhost/:memory:"
|
||||
```
|
||||
|
||||
## Other databases
|
||||
|
||||
See the [documentation for adapters](/schemas/adapters) for more information on advanced configuration, including how to use NextAuth.js with other databases using a [custom adapter](/tutorials/creating-a-database-adapter).
|
||||
See the [documentation for adapters](/adapters/overview) for more information on advanced configuration, including how to use NextAuth.js with other databases using a [custom adapter](/tutorials/creating-a-database-adapter).
|
||||
|
||||
@@ -309,7 +309,7 @@ By default NextAuth.js uses a database adapter that uses TypeORM and supports My
|
||||
|
||||
You can use the `adapter` option to use the Prisma adapter - or pass in your own adapter if you want to use a database that is not supported by one of the built-in adapters.
|
||||
|
||||
See the [adapter documentation](/schemas/adapters) for more information.
|
||||
See the [adapter documentation](/adapters/overview) for more information.
|
||||
|
||||
:::note
|
||||
If the `adapter` option is specified it overrides the `database` option, only specify one or the other.
|
||||
|
||||
@@ -254,22 +254,26 @@ providers: [
|
||||
username: { label: "Username", type: "text", placeholder: "jsmith" },
|
||||
password: { label: "Password", type: "password" }
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
const user = (credentials, req) => {
|
||||
// You need to provide your own logic here that takes the credentials
|
||||
// submitted and returns either a object representing a user or value
|
||||
// that is false/null if the credentials are invalid.
|
||||
// e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
|
||||
// You can also use the request object to obtain additional parameters
|
||||
// (i.e., the request IP address)
|
||||
return null
|
||||
}
|
||||
if (user) {
|
||||
// Any user object returned here will be saved in the JSON Web Token
|
||||
async authorize(credentials, req) {
|
||||
// You need to provide your own logic here that takes the credentials
|
||||
// submitted and returns either a object representing a user or value
|
||||
// that is false/null if the credentials are invalid.
|
||||
// e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
|
||||
// You can also use the `req` object to obtain additional parameters
|
||||
// (i.e., the request IP address)
|
||||
const res = await fetch("/your/endpoint", {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(credentials),
|
||||
headers: { "Content-Type": "application/json" }
|
||||
})
|
||||
const user = await res.json()
|
||||
|
||||
// If no error and we have user data, return it
|
||||
if (res.ok && user) {
|
||||
return user
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
// Return null if user data could not be retrieved
|
||||
return null
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
@@ -266,7 +266,7 @@ You can also set these parameters through [`provider.authorizationParams`](/conf
|
||||
:::
|
||||
|
||||
:::note
|
||||
The following parameters are always overridden server-side: `redirect_uri`, `scope`, `state`
|
||||
The following parameters are always overridden server-side: `redirect_uri`, `state`
|
||||
:::
|
||||
|
||||
---
|
||||
@@ -328,6 +328,24 @@ export default function App ({ Component, pageProps }) {
|
||||
|
||||
If you pass the `session` page prop to the `<Provider>` – as in the example above – you can avoid checking the session twice on pages that support both server and client side rendering.
|
||||
|
||||
This only works on pages where you provide the correct `pageProps`, however. This is normally done in `getInitialProps` or `getServerSideProps` like so:
|
||||
|
||||
```js title="pages/index.js"
|
||||
import { getSession } from "next-auth/client"
|
||||
|
||||
...
|
||||
|
||||
export async function getServerSideProps(ctx) {
|
||||
return {
|
||||
props: {
|
||||
session: await getSession(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If every one of your pages needs to be protected, you can do this in `_app`, otherwise you can do it on a page-by-page basis. Alternatively, there is you can do per page authentication checks client side, instead of having each auth check be blocking (SSR) by using the method described below in [alternative client session handling](#custom-client-session-handling).
|
||||
|
||||
### Options
|
||||
|
||||
The session state is automatically synchronized across all open tabs/windows and they are all updated whenever they gain or lose focus or the state changes in any of them (e.g. a user signs in or out).
|
||||
@@ -386,3 +404,72 @@ The value for `keepAlive` should always be lower than the value of the session `
|
||||
:::note
|
||||
See [**the Next.js documentation**](https://nextjs.org/docs/advanced-features/custom-app) for more information on **_app.js** in Next.js applications.
|
||||
:::
|
||||
|
||||
## Alternatives
|
||||
|
||||
### Custom Client Session Handling
|
||||
|
||||
Due to the way Next.js handles `getServerSideProps` / `getInitialProps`, every protected page load has to make a server-side query to check if the session is valid and then generate the requested page. This alternative solution allows for showing a loading state on the initial check and every page transition afterward will be client-side, without having to check with the server and regenerate pages.
|
||||
|
||||
```js title="pages/admin.jsx"
|
||||
export default function AdminDashboard () {
|
||||
const [session] = useSession()
|
||||
// session is always non-null inside this page, all the way down the React tree.
|
||||
return "Some super secret dashboard"
|
||||
}
|
||||
|
||||
AdminDashboard.auth = true
|
||||
```
|
||||
|
||||
```jsx title="pages/_app.jsx"
|
||||
export default function App({ Component, pageProps }) {
|
||||
return (
|
||||
<SessionProvider session={pageProps.session}>
|
||||
{Component.auth
|
||||
? <Auth><Component {...pageProps} /></Auth>
|
||||
: <Component {...pageProps} />
|
||||
}
|
||||
</SessionProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function Auth({ children }) {
|
||||
const [session, loading] = useSession()
|
||||
const isUser = !!session?.user
|
||||
React.useEffect(() => {
|
||||
if (loading) return // Do nothing while loading
|
||||
if (!isUser) signIn() // If not authenticated, force log in
|
||||
}, [isUser, loading])
|
||||
|
||||
if (isUser) {
|
||||
return children
|
||||
}
|
||||
|
||||
// Session is being fetched, or no user.
|
||||
// If no user, useEffect() will redirect.
|
||||
return <div>Loading...</div>
|
||||
}
|
||||
```
|
||||
|
||||
It can be easily be extended/modified to support something like an options object for role based authentication on pages. An example:
|
||||
|
||||
```jsx title="pages/admin.jsx"
|
||||
AdminDashboard.auth = {
|
||||
role: "admin",
|
||||
loading: <AdminLoadingSkeleton/>,
|
||||
unauthorized: "/login-with-different-user" // redirect to this url
|
||||
}
|
||||
```
|
||||
|
||||
Because of how _app is done, it won't unnecessarily contant the /api/auth/session endpoint for pages that do not require auth.
|
||||
|
||||
More information can be found in the following [Github Issue](https://github.com/nextauthjs/next-auth/issues/1210).
|
||||
|
||||
### NextAuth.js + React-Query
|
||||
|
||||
There is also an alternative client-side API library based upon [`react-query`](https://www.npmjs.com/package/react-query) available under [`nextauthjs/react-query`](https://github.com/nextauthjs/react-query).
|
||||
|
||||
If you use `react-query` in your project already, you can leverage it with NextAuth.js to handle the client-side session management for you as well. This replaces NextAuth.js's native `useSession` and `Provider` from `next-auth/client`.
|
||||
|
||||
See repository [`README`](https://github.com/nextauthjs/react-query) for more details.
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ title: Example Code
|
||||
|
||||
## Get started with NextAuth.js
|
||||
|
||||
The example code below describes to add authentication to a Next.js app.
|
||||
The example code below describes how to add authentication to a Next.js app.
|
||||
|
||||
:::tip
|
||||
The easiest way to get started is to clone the [example app](https://github.com/nextauthjs/next-auth-example) and follow the instructions in README.md. You can try out a live demo at [next-auth-example.now.sh](https://next-auth-example.now.sh)
|
||||
The easiest way to get started is to clone the [example app](https://github.com/nextauthjs/next-auth-example) and follow the instructions in README.md. You can try out a live demo at [next-auth-example.vercel.app](https://next-auth-example.vercel.app)
|
||||
:::
|
||||
|
||||
### Add API route
|
||||
|
||||
@@ -7,6 +7,10 @@ title: WorkOS
|
||||
|
||||
https://workos.com/docs/sso/guide
|
||||
|
||||
## Configuration
|
||||
|
||||
https://dashboard.workos.com
|
||||
|
||||
## Options
|
||||
|
||||
The **WorkOS Provider** comes with a set of default options:
|
||||
@@ -22,10 +26,87 @@ import Providers from `next-auth/providers`
|
||||
...
|
||||
providers: [
|
||||
Providers.WorkOS({
|
||||
clientId: process.env.WORKOS_ID,
|
||||
clientSecret: process.env.WORKOS_SECRET,
|
||||
domain: process.env.WORKOS_DOMAIN
|
||||
clientId: process.env.WORKOS_CLIENT_ID,
|
||||
clientSecret: process.env.WORKOS_API_KEY,
|
||||
}),
|
||||
],
|
||||
...
|
||||
```
|
||||
|
||||
WorkOS is not an identity provider itself, but, rather, a bridge to multiple single sign-on (SSO) providers. As a result, we need to make some additional changes to authenticate users using WorkOS.
|
||||
|
||||
In order to sign a user in using WorkOS, we need to specify which WorkOS Connection to use. A common way to do this is to collect the user's email address and extract the domain.
|
||||
|
||||
This can be done using a custom login page.
|
||||
|
||||
To add a custom login page, you can use the `pages` option:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
pages: {
|
||||
signIn: '/auth/signin',
|
||||
}
|
||||
```
|
||||
|
||||
We can then add a custom login page that displays an input where the user can enter their email address. We then extract the domain from the user's email address and pass it to the `authorizationParams` parameter on the `signIn` function:
|
||||
|
||||
```jsx title="pages/auth/signin.js"
|
||||
import { getProviders, signIn } from 'next-auth/client'
|
||||
|
||||
export default function SignIn({ providers }) {
|
||||
const [email, setEmail] = useState('')
|
||||
|
||||
return (
|
||||
<>
|
||||
{Object.values(providers).map((provider) => {
|
||||
if (provider.id === 'workos') {
|
||||
return (
|
||||
<div key={provider.id}>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
placeholder="Email"
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
<button
|
||||
onClick={() =>
|
||||
signIn(provider.id, undefined, {
|
||||
domain: email.split('@')[1],
|
||||
})
|
||||
}
|
||||
>
|
||||
Sign in with SSO
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={provider.id}>
|
||||
<button onClick={() => signIn(provider.id)}>
|
||||
Sign in with {provider.name}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// This is the recommended way for Next.js 9.3 or newer
|
||||
export async function getServerSideProps(context){
|
||||
const providers = await getProviders()
|
||||
return {
|
||||
props: { providers }
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// If older than Next.js 9.3
|
||||
SignIn.getInitialProps = async () => {
|
||||
return {
|
||||
providers: await getProviders()
|
||||
}
|
||||
}
|
||||
*/
|
||||
```
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
---
|
||||
id: adapters
|
||||
title: Database Adapters
|
||||
---
|
||||
|
||||
An **Adapter** in NextAuth.js connects your application to whatever database or backend system you want to use to store data for user accounts, sessions, etc.
|
||||
|
||||
You do not need to specify an Adapter explicitly unless you want to use advanced options such as custom models or schemas, if you want to use the Prisma Adapter instead of the default TypeORM Adapter, or if you are creating a custom Adapter to connect to a database that is not one of the supported databases.
|
||||
|
||||
### Database Schemas
|
||||
|
||||
Configure your database by creating the tables and columns to match the schema expected by NextAuth.js.
|
||||
|
||||
- [MySQL Schema](/schemas/mysql)
|
||||
- [Postgres Schema](/schemas/postgres)
|
||||
- [Microsoft SQL Server Schema](/schemas/mssql)
|
||||
|
||||
## TypeORM Adapter
|
||||
|
||||
NextAuth.js comes with a default Adapter that uses [TypeORM](https://typeorm.io/) so that it can be used with many different databases without any further configuration, you simply add the node module for the database driver you want to use to your project and pass a database connection string to NextAuth.js.
|
||||
|
||||
The default Adapter is the TypeORM Adapter, the following configuration options are exactly equivalent.
|
||||
|
||||
```javascript
|
||||
database: {
|
||||
type: 'sqlite',
|
||||
database: ':memory:',
|
||||
synchronize: true
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
adapter: Adapters.Default({
|
||||
type: "sqlite",
|
||||
database: ":memory:",
|
||||
synchronize: true,
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
adapter: Adapters.TypeORM.Adapter({
|
||||
type: "sqlite",
|
||||
database: ":memory:",
|
||||
synchronize: true,
|
||||
})
|
||||
```
|
||||
|
||||
The tutorial [Custom models with TypeORM](/tutorials/typeorm-custom-models) explains how to extend the built in models and schemas used by the TypeORM Adapter. You can use these models in your own code.
|
||||
|
||||
:::tip
|
||||
The `synchronize` option in TypeORM will generate SQL that exactly matches the documented schemas for MySQL and Postgres.
|
||||
|
||||
However, it should not be enabled against production databases as it may cause data loss if the configured schema does not match the expected schema!
|
||||
:::
|
||||
|
||||
## Prisma Adapter
|
||||
|
||||
You can also use NextAuth.js with the experimental Adapter for [Prisma 2](https://www.prisma.io/docs/).
|
||||
|
||||
To use this Adapter, you need to install Prisma Client and Prisma CLI:
|
||||
|
||||
```
|
||||
npm install @prisma/client
|
||||
npm install prisma --save-dev
|
||||
```
|
||||
|
||||
Configure your NextAuth.js to use the Prisma Adapter:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
import NextAuth from "next-auth"
|
||||
import Providers from "next-auth/providers"
|
||||
import Adapters from "next-auth/adapters"
|
||||
import { PrismaClient } from "@prisma/client"
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export default NextAuth({
|
||||
providers: [
|
||||
Providers.Google({
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
}),
|
||||
],
|
||||
adapter: Adapters.Prisma.Adapter({ prisma }),
|
||||
})
|
||||
```
|
||||
|
||||
:::tip
|
||||
While Prisma includes an experimental feature in the migration command that is able to generate SQL from a schema, creating tables and columns using the provided SQL is currently recommended instead as SQL schemas automatically generated by Prisma may differ from the recommended schemas.
|
||||
:::
|
||||
|
||||
### Prisma Schema
|
||||
|
||||
Create a schema file in `prisma/schema.prisma` similar to this one:
|
||||
|
||||
```json title="schema.prisma"
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./dev.db"
|
||||
}
|
||||
|
||||
model Account {
|
||||
id Int @default(autoincrement()) @id
|
||||
compoundId String @unique @map(name: "compound_id")
|
||||
userId Int @map(name: "user_id")
|
||||
providerType String @map(name: "provider_type")
|
||||
providerId String @map(name: "provider_id")
|
||||
providerAccountId String @map(name: "provider_account_id")
|
||||
refreshToken String? @map(name: "refresh_token")
|
||||
accessToken String? @map(name: "access_token")
|
||||
accessTokenExpires DateTime? @map(name: "access_token_expires")
|
||||
createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
|
||||
@@index([providerAccountId], name: "providerAccountId")
|
||||
@@index([providerId], name: "providerId")
|
||||
@@index([userId], name: "userId")
|
||||
|
||||
@@map(name: "accounts")
|
||||
}
|
||||
|
||||
model Session {
|
||||
id Int @default(autoincrement()) @id
|
||||
userId Int @map(name: "user_id")
|
||||
expires DateTime
|
||||
sessionToken String @unique @map(name: "session_token")
|
||||
accessToken String @unique @map(name: "access_token")
|
||||
createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
|
||||
@@map(name: "sessions")
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @default(autoincrement()) @id
|
||||
name String?
|
||||
email String? @unique
|
||||
emailVerified DateTime? @map(name: "email_verified")
|
||||
image String?
|
||||
createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
|
||||
@@map(name: "users")
|
||||
}
|
||||
|
||||
model VerificationRequest {
|
||||
id Int @default(autoincrement()) @id
|
||||
identifier String
|
||||
token String @unique
|
||||
expires DateTime
|
||||
createdAt DateTime @default(now()) @map(name: "created_at")
|
||||
updatedAt DateTime @default(now()) @map(name: "updated_at")
|
||||
|
||||
@@map(name: "verification_requests")
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
Set the `datasource` option appropriately for your database:
|
||||
|
||||
```json title="schema.prisma"
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
```
|
||||
|
||||
```json title="schema.prisma"
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Generate Client
|
||||
|
||||
Once you have saved your schema, use the Prisma CLI to generate the Prisma Client:
|
||||
|
||||
```
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
To configure you database to use the new schema (i.e. create tables and columns) use the `prisma migrate` command:
|
||||
|
||||
```
|
||||
npx prisma migrate dev
|
||||
```
|
||||
|
||||
To generate a schema in this way with the above example code, you will need to specify your datbase connection string in the environment variable `DATABASE_URL`. You can do this by setting it in a `.env` file at the root of your project.
|
||||
|
||||
As this feature is experimental in Prisma, it is behind a feature flag. You should check your database schema manually after using this option. See the [Prisma documentation](https://www.prisma.io/docs/) for information on how to use `prisma migrate`.
|
||||
|
||||
### Custom Models
|
||||
|
||||
You can add properties to the schema and map them to any database column names you wish, but you should not change the base properties or types defined in the example schema.
|
||||
|
||||
The model names themselves can be changed with a configuration option, and the datasource can be changed to anything supported by Prisma.
|
||||
|
||||
You can use custom model names by using the `modelMapping` option (shown here with default values).
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
adapter: Adapters.Prisma.Adapter({
|
||||
prisma,
|
||||
modelMapping: {
|
||||
User: 'user',
|
||||
Account: 'account',
|
||||
Session: 'session',
|
||||
VerificationRequest: 'verificationRequest'
|
||||
}
|
||||
})
|
||||
...
|
||||
```
|
||||
|
||||
:::tip
|
||||
If you experience issues with Prisma opening too many database connections in local development mode (e.g. due to Hot Module Reloading) you can use an approach like this when initalising the Prisma Client:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
let prisma
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
prisma = new PrismaClient()
|
||||
} else {
|
||||
if (!global.prisma) {
|
||||
global.prisma = new PrismaClient()
|
||||
}
|
||||
prisma = global.prisma
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Custom Adapter
|
||||
|
||||
See the tutorial for [creating a database Adapter](/tutorials/creating-a-database-adapter) for more information on how to create a custom Adapter. Have a look at the [Adapter repository](https://github.com/nextauthjs/adapters) to see community maintained custom Adapter or add your own.
|
||||
|
||||
### Editor integration
|
||||
|
||||
When writing your own custom Adapter in plain JavaScript, note that you can use **JSDoc** to get helpful editor hints and auto-completion like so:
|
||||
|
||||
```js
|
||||
/** @type { import("next-auth/adapters").Adapter } */
|
||||
const MyAdapter = () => {
|
||||
return {
|
||||
async getAdapter() {
|
||||
return {
|
||||
// your adapter methods here
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
This will work in code editors with a strong TypeScript integration like VSCode or WebStorm. It might not work if you're using more lightweight editors like VIM or Atom.
|
||||
:::
|
||||
@@ -86,3 +86,7 @@ This `dev.to` tutorial walks one through adding NextAuth.js to an existing proje
|
||||
### [Adding Sign in With Apple Next JS](https://thesiddd.com/blog/apple-auth)
|
||||
|
||||
This tutorial walks step by step on how to get Sign In with Apple working (both locally and on a deployed website) using NextAuth.js.
|
||||
|
||||
### [How to Authenticate Next.js Apps with Twitter & NextAuth.js](https://spacejelly.dev/posts/how-to-authenticate-next-js-apps-with-twitter-nextauth-js/)
|
||||
|
||||
Learn how to add Twitter authentication and login to a Next.js app both clientside and serverside with NextAuth.js.
|
||||
|
||||
@@ -3,7 +3,7 @@ id: typeorm-custom-models
|
||||
title: Custom models with TypeORM
|
||||
---
|
||||
|
||||
NextAuth.js provides a set of [models and schemas](/schemas/models) for the built-in TypeORM adapter that you can easily extend.
|
||||
NextAuth.js provides a set of [models and schemas](/adapters/models) for the built-in TypeORM adapter that you can easily extend.
|
||||
|
||||
You can use these models with MySQL, MariaDB, Postgres, MongoDB and SQLite.
|
||||
|
||||
@@ -79,5 +79,3 @@ export default NextAuth({
|
||||
),
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -27,15 +27,27 @@ module.exports = {
|
||||
},
|
||||
{
|
||||
type: "category",
|
||||
label: "Models & Schemas",
|
||||
label: "Database Adapters",
|
||||
collapsed: true,
|
||||
items: [
|
||||
"schemas/models",
|
||||
"schemas/mysql",
|
||||
"schemas/postgres",
|
||||
"schemas/mssql",
|
||||
"schemas/mongodb",
|
||||
"schemas/adapters",
|
||||
"adapters/overview",
|
||||
"adapters/models",
|
||||
{
|
||||
type: "category",
|
||||
label: "TypeORM",
|
||||
collapsed: true,
|
||||
items: [
|
||||
"adapters/typeorm/typeorm-overview",
|
||||
"adapters/typeorm/mysql",
|
||||
"adapters/typeorm/postgres",
|
||||
"adapters/typeorm/mssql",
|
||||
"adapters/typeorm/mongodb",
|
||||
],
|
||||
},
|
||||
"adapters/fauna",
|
||||
"adapters/prisma",
|
||||
"adapters/dynamodb",
|
||||
"adapters/firebase",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -117,7 +117,7 @@ function Home() {
|
||||
"button button--outline button--secondary button--lg rounded-pill",
|
||||
styles.button
|
||||
)}
|
||||
href="https://next-auth-example.now.sh"
|
||||
href="https://next-auth-example.vercel.app"
|
||||
>
|
||||
Live Demo
|
||||
</a>
|
||||
|
||||
10
www/vercel.json
Normal file
10
www/vercel.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"redirects": [
|
||||
{ "source": "/schemas/models", "destination": "/adapters/models", "permanent": true },
|
||||
{ "source": "/schemas/mysql", "destination": "/adapters/typeorm/mysql", "permanent": true },
|
||||
{ "source": "/schemas/postgres", "destination": "/adapters/typeorm/postgres", "permanent": true },
|
||||
{ "source": "/schemas/mssql", "destination": "/adapters/typeorm/mssql", "permanent": true },
|
||||
{ "source": "/schemas/mongodb", "destination": "/adapters/typeorm/mongodb", "permanent": true },
|
||||
{ "source": "/schemas/adapters", "destination": "/adapters/overview", "permanent": true }
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user