@auth/sequelize-adapter
Official Sequilize adapter for Auth.js / NextAuth.js.
Installationβ
- npm
- yarn
- pnpm
npm install next-auth @auth/sequelize-adapter sequelize
yarn add next-auth @auth/sequelize-adapter sequelize
pnpm add next-auth @auth/sequelize-adapter sequelize
default()β
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/configuration/auth-config
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,
}),
},
}),
});
default(
client
:Sequelize
,options
?:SequelizeAdapterOptions
):Adapter
Parametersβ
Parameter | Type |
---|---|
client | Sequelize |
options? | SequelizeAdapterOptions |
Returnsβ
Adapter
SequelizeAdapterOptionsβ
This is the interface of the Sequelize adapter options.
Propertiesβ
models?β
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.
synchronize?β
synchronize:
boolean
Whether to synchronize the models or not.