@auth/sequelize-adapter
Official Sequilize adapter for Auth.js / NextAuth.js.
Installation
npm install next-auth @auth/sequelize-adapter sequelize
models
Re-exports models
SequelizeAdapterOptions
This is the interface of the Sequelize adapter options.
Properties
models?
optional models: Partial<{
Account: ModelCtor<AccountInstance>;
Session: ModelCtor<SessionInstance>;
User: ModelCtor<UserInstance>;
VerificationToken: ModelCtor<VerificationTokenInstance>;
}>;
The Sequelize Models related to Auth.js that will be created in your database.
Type declaration
Account
Account: ModelCtor<AccountInstance>;
Session
Session: ModelCtor<SessionInstance>;
User
User: ModelCtor<UserInstance>;
VerificationToken
VerificationToken: ModelCtor<VerificationTokenInstance>;
synchronize?
optional synchronize: boolean;
Whether to synchronize the models or not.
default()
default(client, options?): Adapter
You’ll also have to manually install the driver for your database of choice.
Setup
Configuring Auth.js
Add this adapter to your pages/api/[...nextauth].js
next-auth configuration object.
import NextAuth from "next-auth"
import SequelizeAdapter from "@auth/sequelize-adapter"
import { Sequelize } from "sequelize"
// https://sequelize.org/master/manual/getting-started.html#connecting-to-a-database
const sequelize = new Sequelize("yourconnectionstring")
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/core#authconfig
export default NextAuth({
// https://authjs.dev/reference/providers/
providers: [],
adapter: SequelizeAdapter(sequelize),
})
Updating the database schema
By default, the sequelize adapter will not create tables in your database. In production, best practice is to create the required tables in your database via migrations. In development, you are able to call sequelize.sync()
to have sequelize create the necessary tables, foreign keys and indexes:
This schema is adapted for use in Sequelize and based upon our main schema
import NextAuth from "next-auth"
import SequelizeAdapter from "@auth/sequelize-adapter"
import Sequelize from 'sequelize'
const sequelize = new Sequelize("sqlite::memory:")
const adapter = SequelizeAdapter(sequelize)
// Calling sync() is not recommended in production
sequelize.sync()
export default NextAuth({
adapter
})
Advanced usage
Using custom models
Sequelize models are option to customization like so:
import NextAuth from "next-auth"
import SequelizeAdapter, { models } from "@auth/sequelize-adapter"
import Sequelize, { DataTypes } from "sequelize"
const sequelize = new Sequelize("sqlite::memory:")
export default NextAuth({
// https://authjs.dev/reference/providers/
providers: [],
adapter: SequelizeAdapter(sequelize, {
models: {
User: sequelize.define("user", {
...models.User,
phoneNumber: DataTypes.STRING,
}),
},
}),
})
Parameters
Parameter | Type |
---|---|
client | Sequelize |
options ? | SequelizeAdapterOptions |