NextAuth Adapter and Provider for Sanity
Database sessions are not implemented, this adapter relies on usage of JSON Web Tokens for stateless session management.
Storing people's user credentials is always a big responsibility. Make sure you understand the risks and inform your users accordingly. This adapter store the user information with the _id
on the user.
path. In other words, these documents can't be queried without authentication, even if your dataset is set to be public. That also means that these documents are available for everyone that's part of your Sanity project.
yarn add next-auth-sanity
npm i next-auth-sanity
import NextAuth, { NextAuthOptions } from 'next-auth';
import GitHub from 'next-auth/providers/github';
import { NextApiRequest, NextApiResponse } from 'next';
import { SanityAdapter, SanityCredentials } from 'next-auth-sanity';
import { client } from 'your/sanity/client';
const options: NextAuthOptions = {
providers: [
GitHub({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET
}),
SanityCredentials(client) // only if you use sign in with credentials
],
session: {
strategy: 'jwt'
},
adapter: SanityAdapter(client)
};
export default NextAuth(options);
you can install this package in your studio project and use the schemas like this
import createSchema from 'part:@sanity/base/schema-creator';
import schemaTypes from 'all:part:@sanity/base/schema-type';
import { user, account, verificationToken } from 'next-auth-sanity/schemas';
export default createSchema({
name: 'default',
types: schemaTypes.concat([user, account, verificationToken])
});
API Route
(with pages)
// pages/api/sanity/signUp.ts
import { signUpHandler } from 'next-auth-sanity';
import { client } from 'your/sanity/client';
export default signUpHandler(client);
Route Handler
(with app directory)
// app/api/sanity/signUp/route.ts
import { signUpHandler } from 'next-auth-sanity';
import { client } from 'your/sanity/client';
export const POST = signUpHandler(client);
Client
import { signUp } from 'next-auth-sanity/client';
import { signIn } from 'next-auth/react';
const user = await signUp({
email,
password,
name
});
await signIn('sanity-login', {
redirect: false,
email,
password
});
if you want to use another schema or upgrade from previous version you can change the default schema used in the library, to do so you can pass a second argument to all methods with config
SanityAdapter(client, {
schemas: {
verificationToken: 'verification-request',
account: 'account',
user: 'profile'
}
})
// the second argument is the name of the user schema
// default: 'user'
SanityCredentials(client, 'profile');
signUpHandler(client, 'profile');
👤 Fedeya hello@fedeminaya.com
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
This README was generated with ❤️ by readme-md-generator