Compare commits

...

22 Commits

Author SHA1 Message Date
ndom91
7e2ff3ee72 chore: rename _app.js file in sandpack 2023-02-18 20:41:39 +01:00
ndom91
9b6bcfe2ce feat: sandpack v2 test 2023-02-18 20:36:09 +01:00
ndom91
26e2f795d8 fix: refactor all to Callout 2023-02-18 18:44:41 +01:00
ndom91
d5eade5ef4 fix: add _meta.json for all sidebar categories and start adding Callouts 2023-02-18 18:12:56 +01:00
Balázs Orbán
2fab7d4cd1 update typedoc-plugin-markdown 2023-01-30 01:57:10 +01:00
Balázs Orbán
177fa44a49 fix formatting, and relative links in nextra 2023-01-19 11:21:03 +01:00
Balázs Orbán
92657bade3 use patched typedoc markdown plugin 2023-01-18 14:42:12 +01:00
Balázs Orbán
581d37b50f Merge branch 'main' into ndom91/docs-rewrite-links 2023-01-18 11:39:38 +01:00
Balázs Orbán
1a928949ce bump nextra 2023-01-18 11:34:55 +01:00
Balázs Orbán
8f222b2e56 fixes 2023-01-16 15:46:07 +01:00
ndom91
01a78e1282 chore: WIP duration hack 2023-01-16 01:20:21 +01:00
ndom91
be481e6fe6 feat: marquee animations 2023-01-16 00:40:52 +01:00
ndom91
e1f5fe3e6d feat: new blob svgs 2023-01-15 23:59:40 +01:00
ndom91
40f754fbca feat: blob design + marquee 2023-01-15 23:46:58 +01:00
ndom91
cf236c6bf3 feat: style landing page 2023-01-15 22:36:13 +01:00
ndom91
b7a38ec7b1 chore: add blob assets 2023-01-15 21:43:45 +01:00
ndom91
db26a4c18d feat: add tailwind and homepage starter 2023-01-15 17:56:50 +01:00
Balázs Orbán
42b55f44f4 remove ignored file 2023-01-13 17:09:37 +01:00
Balázs Orbán
1d3761356a fixes 2023-01-13 17:08:08 +01:00
ndom91
79147f1cf5 fix: typedoc markdown plugin 2023-01-12 22:48:43 +01:00
ndom91
caf63f0eb4 chore(docs): copy over docs 2023-01-12 22:42:43 +01:00
ndom91
7dec2eec71 chore(docs): test nextra docs 2023-01-12 22:13:26 +01:00
235 changed files with 14835 additions and 3019 deletions

View File

@@ -34,11 +34,11 @@ module.exports = {
extends: ["plugin:jest/recommended"],
env: { jest: true },
},
{
files: ["docs/**"],
plugins: ["@docusaurus"],
extends: ["plugin:@docusaurus/recommended"],
},
// {
// files: ["docs/**"],
// plugins: ["@docusaurus"],
// extends: ["plugin:@docusaurus/recommended"],
// },
{
// TODO: Expand to all packages
files: ["packages/{core,sveltekit}/*.ts"],

1
.gitignore vendored
View File

@@ -89,6 +89,7 @@ packages/core/providers
packages/core/src/lib/pages/styles.ts
docs/docs/reference/03-core
docs/docs/reference/04-sveltekit
docs-nextra/pages/reference/core
# SvelteKit

View File

@@ -0,0 +1,19 @@
<!-- <svg width="1077" height="990" viewBox="0 0 1077 990" fill="none" xmlns="http://www.w3.org/2000/svg"> -->
<!-- <path d="M909.079 176.687C486.468 1429.32 94.8519 797.145 -245.666 989.191L-273.518 122.311C-98.0847 109.104 255.784 81.3405 267.79 75.9479C282.798 69.2072 1153.31 -485.661 1071.51 -140.889C1022.28 -26.4819 1001.45 -97.0987 909.079 176.687Z" fill="url(#paint0_linear_228_76)" fill-opacity="1" /> -->
<!-- <defs> -->
<!-- <linearGradient id="paint0_linear_228_76" x1="588.47" y1="791.265" x2="238.137" y2="497.91" gradientUnits="userSpaceOnUse"> -->
<!-- <stop stop-color="#FF4400"/> -->
<!-- <stop offset="1" stop-color="#111" /> -->
<!-- </linearGradient> -->
<!-- </defs> -->
<!-- </svg> -->
<svg width="1056" height="855" viewBox="0 0 1056 855" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M888.078 42.3027C465.467 1294.94 73.851 662.761 -266.667 854.807L-294.519 -12.0732C-119.086 -25.2807 234.783 -53.0438 246.789 -58.4364C261.797 -65.1771 1132.31 -620.045 1050.51 -275.273C1001.28 -160.866 980.447 -231.483 888.078 42.3027Z" fill="url(#paint0_radial_228_76)"/>
<defs>
<radialGradient id="paint0_radial_228_76" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(666.999 571.116) rotate(-129.513) scale(513.947 862.777)">
<stop stop-color="#FF4400"/>
<stop offset="1" stop-color="#111111"/>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,20 @@
<!-- <svg width="1405" height="1025" viewBox="0 0 1405 1025" fill="none" xmlns="http://www.w3.org/2000/svg"> -->
<!-- <path d="M1180.05 977.4C483.802 708.04 103.247 143.506 0 -105.091L1102.61 -196C1418.53 307.367 1876.29 1246.76 1180.05 977.4Z" fill="url(#paint0_linear_228_83)" fill-opacity="0.44"/> -->
<!-- <defs> -->
<!-- <linearGradient id="paint0_linear_228_83" x1="185.171" y1="460.565" x2="641.405" y2="-62.9701" gradientUnits="userSpaceOnUse"> -->
<!-- <stop stop-color="#BB44CC"/> -->
<!-- <stop offset="1" stop-color="#BB44CC" stop-opacity="0"/> -->
<!-- </linearGradient> -->
<!-- </defs> -->
<!-- </svg> -->
<svg width="1405" height="1025" viewBox="0 0 1405 1025" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1180.05 977.4C483.802 708.04 103.247 143.506 0 -105.091L1102.61 -196C1418.53 307.367 1876.29 1246.76 1180.05 977.4Z" fill="url(#paint0_radial_228_83)"/>
<defs>
<radialGradient id="paint0_radial_228_83" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(498 619) rotate(-46.5881) scale(548.572 1194.34)">
<stop stop-color="#BB44CC"/>
<stop offset="1" stop-color="#111111"/>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,20 @@
<!-- <svg width="2402" height="275" viewBox="0 0 2402 275" fill="none" xmlns="http://www.w3.org/2000/svg"> -->
<!-- <path d="M305.668 155.376C1150.52 -387.169 3270.85 708.01 2011.14 262.274L1847.48 804.627C1613.84 721.267 1142.31 553.804 1125.29 550.832C1104 547.117 -168.361 431.431 18.8067 264.119C109.949 220.108 121.011 273.958 305.668 155.376Z" fill="url(#paint0_linear_228_78)" fill-opacity="0.66"/> -->
<!-- <defs> -->
<!-- <linearGradient id="paint0_linear_228_78" x1="869.047" y1="-51.7999" x2="921.583" y2="353.448" gradientUnits="userSpaceOnUse"> -->
<!-- <stop stop-color="#44BBCC"/> -->
<!-- <stop offset="1" stop-color="#44BBCC" stop-opacity="0.12"/> -->
<!-- </linearGradient> -->
<!-- </defs> -->
<!-- </svg> -->
<svg width="2402" height="275" viewBox="0 0 2402 275" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M305.668 155.376C1150.52 -387.169 3270.85 708.01 2011.14 262.274L1847.48 804.627C1613.84 721.267 1142.31 553.804 1125.29 550.832C1104 547.117 -168.361 431.431 18.8067 264.119C109.949 220.108 121.011 273.958 305.668 155.376Z" fill="url(#paint0_radial_228_78)"/>
<defs>
<radialGradient id="paint0_radial_228_78" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(883.5 -66) rotate(93.0267) scale(757.557 879.417)">
<stop stop-color="#44BBCC"/>
<stop offset="1" stop-color="#111111"/>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,66 @@
import { useState, useEffect } from "react"
import { motion } from "framer-motion"
const clamp = (num, min, max) => Math.min(Math.max(num, min), max)
export default function Marquee({ files }) {
const [{ width, height }, setSize] = useState({ height: 0, width: 0 })
useEffect(() => {
setSize({
width: window.innerWidth,
height: window.innerHeight,
})
}, [])
if (width === 0) return
return (
<div className="absolute w-full h-full top-0 left-0 dark:opacity-5 opacity-20 saturate-0 brightness-75 dark:brightness-[1000] -z-20 overflow-hidden flex flex-col marquee-wrapper">
{files.map((name) => (
<MarqueeItem key={name} name={name} width={width} height={height} />
))}
</div>
)
}
function MarqueeItem({ name, width, height }) {
const [y] = useState(height * Math.random())
const [reset, setReset] = useState(false)
const [duration] = useState(clamp(Math.random() * 25, 20, 25))
useEffect(() => {
const timeout =
setTimeout(() => {
setReset(true)
}, (1000 * (width - offset)) / duration) - 2000
return () => clearTimeout(timeout)
}, [duration, width])
const offset = Math.random() * width
return (
<motion.span
key={name + reset}
className="absolute flex items-center justify-center"
initial={{ x: reset ? 0 : offset, y }}
animate={{ x: width }}
transition={{
repeat: Infinity,
duration: reset ? duration : (width - offset) / duration,
ease: "linear",
}}
>
<motion.img
src={`/img/providers/${name}`}
alt={name}
className="relative w-12 drop-shadow-xl"
initial={{ opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={{
delay: reset ? 0 : Math.random() * 5,
duration: 1,
type: "spring",
stiffness: 150,
}}
/>
</motion.span>
)
}

View File

@@ -0,0 +1,61 @@
import { Sandpack } from "@codesandbox/sandpack-react"
import { freeCodeCampDark } from "@codesandbox/sandpack-themes"
export default function AuthSandbox() {
return (
<div style={{ width: "100%" }}>
<Sandpack
template="nextjs"
files={{
"/pages/api/auth/[...nextauth].js": `import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
export const authOptions = {
// Configure one or more authentication providers
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
}
export default NextAuth(authOptions)
`,
"pages/_app.js": `import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}`,
".env": `GITHUB_ID=123abc
GITHUB_SECRET=abc123
NEXTAUTH_SECRET=abcbaerjwiofjlakshfu9fnajs
`,
"/pages/index.js": `export default function App() {
return <div><h1>Hello NextAuth User</h1><a href="/api/auth/signin">Signin</a></div>
}`,
}}
theme={freeCodeCampDark}
customSetup={{
dependencies: {
"next-auth": "latest",
},
}}
options={{
showInlineErrors: true,
showLineNumbers: true,
showTabs: true,
closableTabs: true,
showNavigator: true,
showConsole: true,
showConsoleButton: true,
editorHeight: "70vh",
}}
/>
</div>
)
}

View File

@@ -0,0 +1,85 @@
export default function Triangle({ className }) {
return (
<svg
id="triangle"
viewBox="0 0 445 379"
className={className}
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<style jsx>
{`
@media (prefers-color-scheme: light) {
#triangle-0 {
fill: #000;
}
#triangle-1 {
fill: #ff4400;
}
#triangle-2 {
fill: #bb44cc;
}
#triangle-3 {
fill: #44bbcc;
}
}
`}
</style>
<path
id="triangle-0"
d="M334.033 238.33L222.692 46.7201L111.352 238.33H334.033Z"
fill="#fff"
/>
<path
id="triangle-1"
d="M198.174 1.12812L4.62255 51.2473C1.37638 52.0878 -0.550786 55.4258 0.344333 58.6574L53.7157 251.338C55.1362 256.466 62.0336 257.344 64.6942 252.736L204.874 9.93656C207.535 5.32834 203.325 -0.205751 198.174 1.12812Z"
fill="url(#triangle-1-gradient)"
/>
<path
id="triangle-2"
d="M246.294 1.12825L439.846 51.2473C443.092 52.0879 445.019 55.4259 444.124 58.6574L390.753 251.338C389.332 256.466 382.435 257.344 379.774 252.736L239.594 9.93665C236.933 5.32844 241.143 -0.205634 246.294 1.12825Z"
fill="url(#triangle-2-gradient)"
/>
<path
id="triangle-3"
d="M361.388 286.577L225.585 377.959C223.559 379.322 220.91 379.322 218.885 377.959L83.0814 286.577C78.1672 283.27 80.5079 275.599 86.4311 275.599H358.039C363.962 275.599 366.303 283.27 361.388 286.577Z"
fill="url(#triangle-3-gradient)"
/>
<defs>
<linearGradient
id="triangle-1-gradient"
x1="-1.28386"
y1="52.7769"
x2="134.785"
y2="131.336"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#992900" />
<stop offset="1" stopColor="#FF4400" />
</linearGradient>
<linearGradient
id="triangle-2-gradient"
x1="445.753"
y1="52.7769"
x2="309.684"
y2="131.336"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#6D2178" />
<stop offset="1" stopColor="#BB44CC" />
</linearGradient>
<linearGradient
id="triangle-3-gradient"
x1="222.236"
y1="380.213"
x2="222.236"
y2="275.599"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#1B5B64" />
<stop offset="1" stopColor="#44BBCC" />
</linearGradient>
</defs>
</svg>
)
}

View File

@@ -0,0 +1,26 @@
import withNextra from "nextra"
import RemarkLinkRewrite from "remark-link-rewrite"
export default withNextra({
theme: "nextra-theme-docs",
themeConfig: "./theme.config.jsx",
mdxOptions: {
format: "detect",
remarkPlugins: [
[
RemarkLinkRewrite,
{
replacer(url) {
if (url.includes(".md")) {
url = url.replace(/\.md$/, "").replace(".md#", "#")
}
if (url.startsWith("https://authjs.dev")) {
url = url.replace("https://authjs.dev", "")
}
return url
},
},
],
],
},
})()

31
docs-nextra/package.json Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "docs-nextra",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"typedoc": "typedoc",
"dev": "TYPEDOC_WATCH=1 pnpm typedoc & next dev",
"start": "next start",
"build": "next build"
},
"keywords": [],
"author": "ndom91 <yo@ndo.dev> (https://ndo.dev/)",
"license": "MIT",
"dependencies": {
"@codesandbox/sandpack-react": "^2.0.6",
"@codesandbox/sandpack-themes": "^2.0.1",
"framer-motion": "^8.4.3",
"next": "13.1.1",
"nextra": "^2.2.5",
"nextra-theme-docs": "^2.2.5",
"remark-link-rewrite": "^1.0.6",
"typedoc": "^0.23.24",
"typedoc-plugin-markdown": "next"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.4"
}
}

View File

@@ -0,0 +1,5 @@
import "../styles/index.css"
export default function NextraApp({ Component, pageProps }) {
return ( <Component {...pageProps} />)
}

View File

@@ -0,0 +1,32 @@
{
"docs": {
"title": "Docs",
"type": "page",
"href": "/getting-started/introduction"
},
"frameworks": {
"title": "Frameworks",
"type": "page",
"href": "/reference"
},
"index": {
"title": "Home",
"theme": {
"sidebar": false,
"layout": "raw"
}
},
"getting-started": "Getting Started",
"guides": "Guides",
"reference": "Reference",
"concepts": "Concepts",
"--": {
"type": "separator"
},
"contributors": "Contributors",
"github-link": {
"title": "Auth.js Repo",
"href": "https://github.com/nextauthjs/next-auth",
"newWindow": true
}
}

View File

@@ -0,0 +1,4 @@
{
"faq": "FAQ",
"oauth": "OAuth"
}

View File

@@ -0,0 +1,359 @@
---
id: faq
title: Frequently Asked Questions
---
## About Auth.js
### Is Auth.js commercial software?
Auth.js is an open source project built by individual contributors.
It is not commercial software and is not associated with a commercial organization.
---
## Compatibility
<details>
<summary>
<h3 style={{display:"inline-block"}}>What databases does Auth.js support?</h3>
</summary>
<p>
You can use Auth.js with MySQL, MariaDB, Postgres, MongoDB and SQLite or without a database. (See our [using a database adapter guide](/guides/adapters/using-a-database-adapter)).
You can use also Auth.js with any database using a custom database adapter, or by using a custom credentials authentication provider - e.g. to support signing in with a username and password stored in an existing database.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>What authentication services does Auth.js support?</h3>
</summary>
<p>
<p>Auth.js includes built-in support for signing in with&nbsp;
(See also: <a href="/reference/providers/oauth-builtin">Providers</a>)
</p>
Auth.js also supports email for passwordless sign in, which is useful for account recovery or for people who are not able to use an account with the configured OAuth services (e.g. due to service outage, account suspension or otherwise becoming locked out of an account).
You can also use a custom based provider to support signing in with a username and password stored in an external database and/or using two factor authentication.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Does Auth.js support signing in with a username and password?</h3>
</summary>
<p>
Auth.js is designed to avoid the need to store passwords for user accounts.
If you have an existing database of usernames and passwords, you can use a custom credentials provider to allow signing in with a username and password stored in an existing database.
_If you use a custom credentials provider user accounts will not be persisted in a database by Auth.js (even if one is configured). The option to use JSON Web Tokens for session tokens (which allow sign in without using a session database) must be enabled to use a custom credentials provider._
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Can I use Auth.js with a website that does not use Next.js?</h3>
</summary>
<p>
Auth.js is designed for use with Next.js and Serverless.
If you are using a different framework for your website, you can create a website that handles sign in with Next.js and then access those sessions on a website that does not use Next.js as long as the websites are on the same domain.
If you use Auth.js on a website with a different subdomain then the rest of your website (e.g. `auth.example.com` vs `www.example.com`) you will need to set a custom cookie domain policy for the Session Token cookie. (See also: [Cookies](/reference/configuration/auth-config#cookies))
Auth.js does not currently support automatically signing into sites on different top level domains (e.g. `www.example.com` vs `www.example.org`) using a single session.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Can I use Auth.js with React Native?</h3>
</summary>
<p>
Auth.js is designed as a secure, confidential client and implements a server side authentication flow.
It is not intended to be used in native applications on desktop or mobile applications, which typically implement public clients (e.g. with client / secrets embedded in the application).
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Is Auth.js supporting TypeScript?</h3>
</summary>
<p>
Yes! Check out the [TypeScript docs](/getting-started/typescript)
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Is Auth.js compatible with Next.js 12 Middleware?</h3>
</summary>
<p>
[Next.js Middleware](https://nextjs.org/docs/middleware) is supported. Head over to the [this page](/reference/nextjs/#middleware)
</p>
</details>
---
## Databases
<details>
<summary>
<h3 style={{display:"inline-block"}}>What databases are supported by Auth.js?</h3>
</summary>
<p>
Auth.js can be used with MySQL, Postgres, MongoDB, SQLite and compatible databases (e.g. MariaDB, Amazon Aurora, Amazon DocumentDB…) or with no database.
It also provides an Adapter API which allows you to connect it to any database.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>What does Auth.js use databases for?</h3>
</summary>
<p>
Databases in Auth.js are used for persisting users, OAuth accounts, email sign in tokens and sessions.
Specifying a database is optional if you don't need to persist user data or support email sign in. If you don't specify a database then JSON Web Tokens will be enabled for session storage and used to store session data.
If you are using a database with Auth.js, you can still explicitly enable JSON Web Tokens for sessions (instead of using database sessions).
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>Should I use a database?</h3>
</summary>
<p>
- Using Auth.js without a database works well for internal tools - where you need to control who is able to sign in, but when you do not need to create user accounts for them in your application.
- Using Auth.js with a database is usually a better approach for a consumer facing application where you need to persist accounts (e.g. for billing, to contact customers, etc).
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>What database should I use?</h3>
</summary>
<p>
Managed database solutions for MySQL, Postgres and MongoDB (and compatible databases) are well supported from cloud providers such as Amazon, Google, Microsoft and Atlas.
If you are deploying directly to a particular cloud platform you may also want to consider serverless database offerings they have (e.g. [Amazon Aurora Serverless on AWS](https://aws.amazon.com/rds/aurora/serverless/)).
</p>
</details>
---
## Security
Parts of this section has been moved to its [own page](/getting-started/security).
<details>
<summary>
<h3 style={{display:"inline-block"}}>How do I get Refresh Tokens and Access Tokens for an OAuth account?</h3>
</summary>
<p>
Auth.js provides a solution for authentication, session management and user account creation.
Auth.js records Refresh Tokens and Access Tokens on sign in (if supplied by the provider) and it will pass them, along with the User ID, Provider and Provider Account ID, to either:
1. A database - if a database connection string is provided
2. The JSON Web Token callback - if JWT sessions are enabled (e.g. if no database specified)
You can then look them up from the database or persist them to the JSON Web Token.
Note: Auth.js does not currently handle Access Token rotation for OAuth providers for you, however you can check out [this tutorial](/guides/basics/refresh-token-rotation) if you want to implement it.
We also have an [example repository](https://github.com/nextauthjs/next-auth-refresh-token-example) / project based upon Auth.js v4 where we demonstrate how to use a refresh token to refresh the provided access token.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>When I sign in with another account with the same email address, why are accounts not linked automatically?</h3>
</summary>
<p>
Automatic account linking on sign in is not secure between arbitrary providers - with the exception of allowing users to sign in via an email addresses as a fallback (as they must verify their email address as part of the flow).
When an email address is associated with an OAuth account it does not necessarily mean that it has been verified as belonging to account holder — how email address verification is handled is not part of the OAuth specification and varies between providers (e.g. some do not verify first, some do verify first, others return metadata indicating the verification status).
With automatic account linking on sign in, this can be exploited by bad actors to hijack accounts by creating an OAuth account associated with the email address of another user.
For this reason it is not secure to automatically link accounts between arbitrary providers on sign in, which is why this feature is generally not provided by authentication service and is not provided by Auth.js.
Automatic account linking is seen on some sites, sometimes insecurely. It can be technically possible to do automatic account linking securely if you trust all the providers involved to ensure they have securely verified the email address associated with the account, but requires placing trust (and transferring the risk) to those providers to handle the process securely.
Examples of scenarios where this is secure include with an OAuth provider you control (e.g. that only authorizes users internal to your organization) or with a provider you explicitly trust to have verified the users email address.
Automatic account linking is not a planned feature of Auth.js, however there is scope to improve the user experience of account linking and of handling this flow, in a secure way. Typically this involves providing a fallback option to sign in via email, which is already possible (and recommended), but the current implementation of this flow could be improved on.
Providing support for secure account linking and unlinking of additional providers - which can only be done if a user is already signed in already - was originally a feature in v1.x but has not been present since v2.0, is planned to return in a future release.
</p>
</details>
---
## Feature Requests
<details>
<summary>
<h3 style={{display:"inline-block"}}>Why doesn't Auth.js support [a particular feature]?</h3>
</summary>
<p>
Auth.js is an open source project built by individual contributors who are volunteers writing code and providing support in their spare time.
If you would like Auth.js to support a particular feature, the best way to help make it happen is to raise a feature request describing the feature and offer to work with other contributors to develop and test it.
If you are not able to develop a feature yourself, you can offer to sponsor someone to work on it.
</p>
</details>
<details>
<summary>
<h3 style={{display:"inline-block"}}>I disagree with a design decision, how can I change your mind?</h3>
</summary>
<p>
Product design decisions on Auth.js are made by core team members.
You can raise suggestions as feature requests / requests for enhancement.
Requests that provide the detail requested in the template and follow the format requested may be more likely to be supported, as additional detail prompted in the templates often provides important context.
Ultimately if your request is not accepted or is not actively in development, you are always free to fork the project under the terms of the ISC License.
</p>
</details>
---
## JSON Web Tokens
<details>
<summary>
<h3>Does Auth.js use JSON Web Tokens?</h3>
</summary>
<p>
Auth.js by default uses JSON Web Tokens for saving the user's session. However, if you use a [database adapter](/guides/adapters/using-a-database-adapter), the database will be used to persist the user's session. You can force the usage of JWT when using a database [through the configuration options](/reference/configuration/auth-config#session). Since v4 all our JWT tokens are now encrypted by default with A256GCM.
</p>
</details>
<details>
<summary>
<h3>What are the advantages of JSON Web Tokens?</h3>
</summary>
<p>
JSON Web Tokens can be used for session tokens, but are also used for lots of other things, such as sending signed objects between services in authentication flows.
- Advantages of using a JWT as a session token include that they do not require a database to store sessions, this can be faster and cheaper to run and easier to scale.
- JSON Web Tokens in Auth.js are secured using cryptographic encryption (JWE) to store the included information directly in a JWT session token. You may then use the token to pass information between services and APIs on the same domain without having to contact a database to verify the included information.
- You can use JWT to securely store information you do not mind the client knowing even without encryption, as the JWT is stored in a server-readable-only cookie so data in the JWT is not accessible to third party JavaScript running on your site.
</p>
</details>
<details>
<summary>
<h3>What are the disadvantages of JSON Web Tokens?</h3>
</summary>
<p>
- You cannot as easily expire a JSON Web Token - doing so requires maintaining a server side blocklist of invalid tokens (at least until they expire) and checking every token against the list every time a token is presented.
Shorter session expiry times are used when using JSON Web Tokens as session tokens to allow sessions to be invalidated sooner and simplify this problem.
Auth.js client includes advanced features to mitigate the downsides of using shorter session expiry times on the user experience, including automatic session token rotation, optionally sending keep alive messages to prevent short lived sessions from expiring if there is an window or tab open, background re-validation, and automatic tab/window syncing that keeps sessions in sync across windows any time session state changes or a window or tab gains or loses focus.
- As with database session tokens, JSON Web Tokens are limited in the amount of data you can store in them. There is typically a limit of around 4096 bytes per cookie, though the exact limit varies between browsers, proxies and hosting services. If you want to support most browsers, then do not exceed 4096 bytes per cookie. If you want to save more data, you will need to persist your sessions in a database (Source: [browsercookielimits.iain.guru](http://browsercookielimits.iain.guru/))
The more data you try to store in a token and the more other cookies you set, the closer you will come to this limit. Since v4 we have implemented cookie chunking so that cookies over the 4kb limit get split and reassembled upon parsing. However since this data needs to be transmitted on every request, if you wish to store more than ~4 KB of data you're probably at the point where you want to store a unique ID in the token and persist the data elsewhere (e.g. in a server-side key/value store).
- Data stored in an encrypted JSON Web Token (JWE) may be compromised at some point.
Even if appropriately configured, information stored in an encrypted JWT should not be assumed to be impossible to decrypt at some point - e.g. due to the discovery of a defect or advances in technology.
Avoid storing any data in a token that might be problematic if it were to be decrypted in the future.
- If you do not explicitly specify a secret for for Auth.js, existing sessions will be invalidated any time your Auth.js configuration changes, as Auth.js will default to an auto-generated secret. Since v4 this only impacts development and generating a secret is required in production.
</p>
</details>
<details>
<summary>
<h3>Are JSON Web Tokens secure?</h3>
</summary>
<p>
By default tokens are not signed (JWS) but are encrypted (JWE). Since v4 we have implemented cookie chunking so that cookies over the 4kb limit get split and reassembled upon parsing.
You can specify other valid algorithms - [as specified in RFC 7518](https://tools.ietf.org/html/rfc7517) - with either a secret (for symmetric encryption) or a public/private key pair (for asymmetric encryption).
Auth.js will generate keys for you, but this will generate a warning at start up.
Using explicit public/private keys for signing is strongly recommended.
</p>
</details>
<details>
<summary>
<h3>What signing and encryption standards does Auth.js support?</h3>
</summary>
<p>
Auth.js includes a largely complete implementation of JSON Object Signing and Encryption (JOSE):
- [RFC 7515 - JSON Web Signature (JWS)](https://tools.ietf.org/html/rfc7515)
- [RFC 7516 - JSON Web Encryption (JWE)](https://tools.ietf.org/html/rfc7516)
- [RFC 7517 - JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517)
- [RFC 7518 - JSON Web Algorithms (JWA)](https://tools.ietf.org/html/rfc7518)
- [RFC 7519 - JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519)
This incorporates support for:
- [RFC 7638 - JSON Web Key Thumbprint](https://tools.ietf.org/html/rfc7638)
- [RFC 7787 - JSON JWS Unencoded Payload Option](https://tools.ietf.org/html/rfc7797)
- [RFC 8037 - CFRG Elliptic Curve ECDH and Signatures](https://tools.ietf.org/html/rfc8037)
</p>
</details>

View File

@@ -0,0 +1,53 @@
---
title: How OAuth works
---
import { Callout } from 'nextra-theme-docs'
Authentication Providers in **Auth.js** are OAuth definitions that allow your users to sign in with their favorite preexisting logins. You can use any of our many predefined providers, or write your own custom OAuth configuration.
- [Using a built-in OAuth Provider](#built-in-providers) (e.g Github, Twitter, Google, etc...)
- [Using a custom OAuth Provider](#using-a-custom-provider)
<Callout>
Auth.js is designed to work with any OAuth service, it supports **OAuth 1.0**, **1.0A**, **2.0** and **OpenID Connect** and has built-in support for most popular sign-in services.
</Callout>
Without going into too much detail, the OAuth flow generally has 6 parts:
1. The application requests authorization to access service resources from the user
2. If the user authorized the request, the application receives an authorization grant
3. The application requests an access token from the authorization server (API) by presenting authentication of its own identity, and the authorization grant
4. If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token to the application. Authorization is complete.
5. The application requests the resource from the resource server (API) and presents the access token for authentication
6. If the access token is valid, the resource server (API) serves the resource to the application
```mermaid
sequenceDiagram
participant Browser
participant App Server
participant Auth Server (Github)
Note left of Browser: User clicks on "Sign in"
Browser->>App Server: GET<br/>"api/auth/signin"
App Server->>App Server: Computes the available<br/>sign in providers<br/>from the "providers" option
App Server->>Browser: Redirects to Sign in page
Note left of Browser: Sign in options<br/>are shown the user<br/>(Github, Twitter, etc...)
Note left of Browser: User clicks on<br/>"Sign in with Github"
Browser->>App Server: POST<br/>"api/auth/signin/github"
App Server->>App Server: Computes sign in<br/>options for Github<br/>(scopes, callback URL, etc...)
App Server->>Auth Server (Github): GET<br/>"github.com/login/oauth/authorize"
Note left of Auth Server (Github): Sign in options<br> are supplied as<br/>query params<br/>(clientId, <br/>scope, etc...)
Auth Server (Github)->>Browser: Shows sign in page<br/>in Github.com<br/>to the user
Note left of Browser: User inserts their<br/>credentials in Github
Browser->>Auth Server (Github): Github validates the inserted credentials
Auth Server (Github)->>Auth Server (Github): Generates one time access code<br/>and calls callback<br>URL defined in<br/>App settings
Auth Server (Github)->>App Server: GET<br/>"api/auth/github/callback?code=123"
App Server->>App Server: Grabs code<br/>to exchange it for<br/>access token
App Server->>Auth Server (Github): POST<br/>"github.com/login/oauth/access_token"<br/>{code: 123}
Auth Server (Github)->>Auth Server (Github): Verifies code is<br/>valid and generates<br/>access token
Auth Server (Github)->>App Server: { access_token: 16C7x... }
App Server->>App Server: Generates session token<br/>and stores session
App Server->>Browser: You're now logged in!
```
For more details, check out Aaron Parecki's blog post [OAuth2 Simplified](https://aaronparecki.com/oauth-2-simplified/) or Postman's blog post [OAuth 2.0: Implicit Flow is Dead, Try PKCE Instead](https://blog.postman.com/pkce-oauth-how-to/).

View File

@@ -0,0 +1,41 @@
## Core team
Without these people, the project could not have become one of the most used authentication libraries in its category.
- [Balázs Orbán](https://github.com/balazsorban44) - **Lead Maintainer**
- [Thang Vu](https://github.com/ThangHuuVu) - Maintainer (Core)
- [Nico Domino](https://github.com/ndom91) - Maintainer (Core, Documentation)
- [Lluis Agusti](https://github.com/lluia) - Maintainer (Documentation, Testing, TypeScript)
## Special thanks
Special thanks to Lori Karikari for creating most of the original provider configurations, to Fredrik Pettersen for creating the original Prisma Adapter, to Gerald Nolan for adding support for Sign in with Apple, and to Jefferson Bledsoe for working on the original testing automation.
- [Lori Karikari](https://github.com/LoriKarikari)
- [Fredrik Pettersen](https://github.com/Fumler)
- [Gerald Nolan](https://github.com/geraldnolan)
- [Jefferson Bledsoe](https://github.com/JeffersonBledsoe)
## Other contributors
Auth.js as it exists today has been possible thanks to the work of many individual contributors.
Thank you to the [dozens of individual contributors](https://github.com/nextauthjs/next-auth/graphs/contributors) who have helped shape Auth.js.
## Open Collective
You can find Auth.js on Open Collective. We are very thankful for all of our existing contributors and would be delighted if you or your company would decide to join them.
More information can be found at: https://opencollective.com/nextauth
## History
- NextAuth.js was originally developed by <a href="https://github.com/iaincollins">Iain Collins</a> in 2016 for Next.js.
- In 2020, NextAuth.js was rebuilt from the ground up to support Serverless, with support for MySQL, Postgres and MongoDB, JSON Web Tokens and built-in support for over a dozen authentication providers.
- In 2021, efforts have started to move NextAuth.js to other frameworks and to support as many databases and providers as possible.
- In 2022, NextAuth.js was rebranded to Auth.js and became framework/runtime agnostic. The core library `@auth/core` was written by <a href="https://twitter.com/balazsorban44">Balázs Orbán</a>
- In 2023 // TODO: 👀🤫

View File

@@ -0,0 +1,12 @@
{
"credentials-tutorial": "Credentials Authentication",
"databases": "Databases",
"email-tutorial": "Email Authentication",
"introduction": "Introduction",
"oauth-tutorial": "OAuth Authentication",
"typescript": "Typescript",
"security": "Security",
"img": {
"display": "hidden"
}
}

View File

@@ -0,0 +1,58 @@
---
title: Credentials Authentication
---
import { Callout } from 'nextra-theme-docs'
Auth.js is built in a way that is flexible to integrate it with any authentication back-end you or your company may already have.
This library has been designed to handle the user session client-wise, to support multiple authentication methods (OAuth, Email, etc...) so that you're not forced to run your own authentication service.
In case you already have an authentication service, you can use the Credentials Provider, which will just forward the credentials inserted by the user in the login form to your service.
For this tutorial, we're going to use [Auth.js example app](https://github.com/nextauthjs/next-auth-example) as a base.
<Callout type="warning">
The functionality provided for credentials based authentication is intentionally limited to discourage use of passwords due to the inherent security risks associated with them and the additional complexity associated with supporting usernames and passwords.
</Callout>
Integrating the Credentials Provider is as simple as initializing it in the Auth.js configuration file:
```ts title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
export default NextAuth({
providers: [
CredentialsProvider({
async authorize(credentials) {
const authResponse = await fetch("/users/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(credentials),
})
if (!authResponse.ok) {
return null
}
const user = await authResponse.json()
return user
},
}),
],
})
```
<Callout type="info">
Check the [Credentials Provider options](/reference/providers/credentials) for further customization
</Callout>
Note that we only need to define an `authorize` method that is in charge of receiving the credentials inserted by the user and call the authorization service.
<Callout type="info">
If you're using TypeScript, you can [augment the `User` interface](/getting-started/typescript#module-augmentation) to match the response of your `authorize` callback, so whenever you read the user in other callbacks (like the `jwt`) the type will match correctly.
</Callout>

View File

@@ -0,0 +1,22 @@
---
title: Databasess
---
import { Callout } from 'nextra-theme-docs'
Auth.js offers multiple database adapters. Check our guides on:
- [Using an existing database adapter](/guides/adapters/using-a-database-adapter)
- [Creating your own](/guides/adapters/creating-a-database-adapter)
<Callout type="info">
As of **v4** Auth.js no longer ships with an adapter included by default. If you would like to persist any information, you need to install one of the many available adapters yourself. See the individual adapter documentation pages for more details.
</Callout>
To learn more about databases in Auth.js and how they are used, check out [databases in the FAQ](/concepts/faq#databases).
---
## How to use a database
See the [documentation for adapters](/reference/adapters/overview) for more information on advanced configuration, including how to use Auth.js with other databases using a [custom adapter](/guides/adapters/creating-a-database-adapter).

View File

@@ -0,0 +1,212 @@
---
title: Email authentication
---
import { Callout } from "nextra-theme-docs"
import Image from "next/image"
import smtpConfig from "./img/dashboard-smtp.png"
import startPageImg from "./img/email-tutorial-start.png"
import checkPageImg from "./img/email-tutorial-check.png"
import mailboxImg from "./img/email-tutorial-mailbox.png"
import loggedInImg from "./img/email-tutorial-logged.png"
Aside from authenticating users in Auth.js via [OAuth](/getting-started/oauth-tutorial), you can also enable the option to authenticate them via "magic links". These are links that are sent to the user's email and when clicking on them they'll sign up the user automatically.
Adding support for signing in via email in addition to one or more OAuth services provides a way for users to sign in if they lose access to their OAuth account (e.g. if it is locked or deleted).
The Email provider can be used in conjunction with (or instead of) one or more OAuth providers.
## How it works
On initial sign in, a **Verification Token** is sent to the email address provided. By default this token **is valid for 24 hours**. If the Verification Token is used within that time (i.e. by clicking on the link in the email) an account is created for the user and they are signed in.
<Callout>
The Email Provider can be used with both JSON Web Tokens and database
sessions, but you [must configure a database
adapter](/guides/adapters/using-a-database-adapter) to use it. It is not
possible to enable email sign in without using a database.
</Callout>
## 1. Installing `nodemailer`
[`nodemailer`](https://www.npmjs.com/package/nodemailer) is a [peer dependency](https://nodejs.org/en/blog/npm/peer-dependencies/) when using the Email Provider. This means we need to install before we can start sending emails:
```bash npm2yarn2pnpm
npm install -D nodemailer
```
`nodemailer` will enable us to send emails from NodeJS, which the runtime on which Next.js application operate.
## 2. Setting up a SMTP service
Next we need a [SMTP service](https://sendgrid.com/blog/what-is-an-smtp-server/) which will be in charge of sending emails from our application. There's a number of services available for this, however [here are the ones](http://nodemailer.com/smtp/well-known/) known to work with `nodemailer`.
<Callout>
For this tutorial, we're going to be using [Sendgrid](https://sendgrid.com/),
but any of the services linked above should work the same
</Callout>
First create an account in and then login to the dashboard, then navigate to "Settings → API Keys" and create an API key:
<Image src={smtpConfig} />
Next paste the API in your terminal as so, and run the command:
```bash
echo -n '<YOUR_API_KEY>' | openssl base64
```
Next, as [per Sendgrid documentation](https://docs.sendgrid.com/for-developers/sending-email/integrating-with-the-smtp-api), let's add the following [environment variables](https://nextjs.org/docs/basic-features/environment-variables) in our Next.js app:
```bash title=".env.local"
SMTP_USER=apikey
SMTP_PASSWORD={API_KEY}
SMTP_HOST=smtp.sendgrid.net
SMTP_PORT=587
EMAIL_FROM={SENDER_EMAIL}
```
Note that we're also specifying from which domain email are going to be sent from. You're going to need to verify [a sender identity](https://docs.sendgrid.com/for-developers/sending-email/sender-identity) so that Sendgrid can send emails from your domain.
Nice! We're getting there. Now we need to read supply this values as the configuration for our Email Provider. Open `pages/api/auth/[...nextauth].ts` and do the following:
```ts title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import EmailProvider from "next-auth/providers/email"
export default NextAuth({
providers: [
Email({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: Number(process.env.EMAIL_SERVER_PORT),
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
},
},
from: process.env.EMAIL_FROM,
}),
],
})
```
## 3. Setting up an adapter
Finally, we'll need to set up a database adapter to store verification tokens the Email Provider will emit when verifying users.
An **Adapter** in Auth.js connects your application to whatever database or backend system you want to use to store data for users, their accounts, sessions, etc...
For this tutorial, we're going to use the **MongoDB** adapter, other any of the other adapters will work just fine.
First, let's start by installing the adapter package:
```bash npm2yarn2pnpm
npm install -D @next-auth/mongodb-adapter mongodb
```
and create a simple MongoDB client:
```ts title="lib/mongodb/client.ts"
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb"
const uri = process.env.MONGODB_URI
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local")
}
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
```
And now let's reference this new adapter from our Auth.js configuration file:
```diff title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import EmailProvider from "next-auth/providers/email"
+ import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
+ import clientPromise from "../../../lib/mongodb/client"
export default NextAuth({
secret: process.env.NEXTAUTH_SECRET,
providers: [
+ adapter: MongoDBAdapter(clientPromise),
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM
}),
],
})
```
## 4. Wiring all together
Now that everything is properly configured, let's try to sign in via email on our application.
Let's start by running a Next.js application with NextAuth, making sure the **EmailProvider** and a Database Adapter are properly configured as per the instructions above.
For this tutorial we're going to be using NextAuth example app. Launch the app and click on "Sign in", we're redirected to the Sign In page:
<Image src={startPageImg} alt="Screenshot of sign in page" />
<Callout>
You can customize the look and feel of your Sign in page pretty easily with
NextAuth. Refer to our [pages guide](/guides/basics/pages) for that!
</Callout>
Then we insert the email address we want to log-in with in the Email credentials section and click on "Sign in with Email".
NextAuth will then display another page hinting the user to check their email:
<Image src={checkPageImg} alt="Screenshot of check email page" />
Let's now check our email, and look for one sent from NextAuth (check your spam folder just in case):
<Image src={mailboxImg} alt="Screenshot of mailbox" />
Nice! We got one, coming from the sender specified in the `EMAIL_FROM` environment variable from our configuration above and that's is the sender we verified in Sengrid.
Click on "Sign in" and a new browser tab will open, you should then land on your application as authenticated!
<Image src={loggedInImg} alt="Screenshot of logged in" />
Easy right? We had to configure Sendgrid and install a database adapter so the user sessions can be saved somewhere, but once done NextAuth will deal with all the user session management for us in a secure way!
<Callout>
A user account (i.e. an entry in the Users table) will not be created for the
user until the first time they verify their email address. If an email address
is already associated with an account, the user will be signed in to that
account when they use the link in the email.
</Callout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

View File

@@ -0,0 +1,56 @@
---
title: Introduction
sidebar_position: 0
---
## About Auth.js
Auth.js is a complete open-source authentication solution for [Next.js](http://nextjs.org/) applications.
It is designed from the ground up to support Next.js and Serverless.
Check our tutorials to see how easy it is to use Auth.js for authentication:
- [Setup with OAuth](/getting-started/oauth-tutorial)
- [Setup with magic links](/getting-started/email-tutorial)
- [Integrating with external auth](/getting-started/credentials-tutorial)
### Flexible and easy to use
- Designed to work with any OAuth service, it supports OAuth 1.0, 1.0A, 2.0 and OpenID Connect
- Built-in support for [many popular sign-in services](/reference/providers/oauth-builtin)
- Supports [email / passwordless authentication](/getting-started/email-tutorial)
- Supports stateless authentication with [any backend](/getting-started/credentials-tutorial) (Active Directory, LDAP, etc)
- Supports both JSON Web Tokens and database sessions
- Designed for Serverless but runs anywhere (AWS Lambda, Docker, Heroku, etc…)
### Own your own data
Auth.js can be used with or without a database.
- An open-source solution that allows you to keep control of your data
- Supports Bring Your Own Database (BYOD) and can be used with any database
- Built-in support for [MySQL, MariaDB, Postgres, SQL Server, MongoDB and SQLite](/getting-started/databases)
- Works great with databases from popular hosting providers
- Can also be used _without a database_ (e.g. OAuth + JWT)
_Note: Email sign-in requires a database to be configured to store single-use verification tokens._
### Secure by default
- Promotes the use of passwordless sign-in mechanisms
- Designed to be secure by default and encourage best practices for safeguarding user data
- Uses Cross-Site Request Forgery Tokens on POST routes (sign in, sign out)
- Default cookie policy aims for the most restrictive policy appropriate for each cookie
- When JSON Web Tokens are enabled, they are encrypted by default (JWE) with A256GCM
- Auto-generates symmetric signing and encryption keys for developer convenience
- Features tab/window syncing and keepalive messages to support short-lived sessions
- Attempts to implement the latest guidance published by [Open Web Application Security Project](https://owasp.org/)
Advanced options allow you to define your own routines to handle controlling what accounts are allowed to sign in, for encoding and decoding JSON Web Tokens and to set custom cookie security policies and session properties, so you can control who can sign in and how often sessions have to be re-validated.
## Credits
Auth.js is an open-source project that is only possible [thanks to contributors](/contributors).
If you would like to financially support the development of Auth.js, you can find more information on our [OpenCollective](https://opencollective.com/nextauth) page.

View File

@@ -0,0 +1,302 @@
---
title: OAuth authentication
---
import { Callout } from "nextra-theme-docs"
import Image from "next/image"
import creatingOauthAppImg from "./img/getting-started-creating-oauth-app.png"
import addingCallbackUrlImg from "./img/getting-started-oauth-callback-url.png"
import gettingClientIdSecretImg from "./img/getting-started-oauth-clientid-secret.png"
import startAppAndSignInImg from "./img/getting-started-app-start.png"
import githubAuthCredentials from "./img/getting-started-github-auth.png"
import nextAuthUserLoggedIn from "./img/getting-started-nextauth-success.png"
We know, authentication is hard. Is a rabbit hole and it's easy to get lost on it. The goal of making Auth.js is that you can add authentication easily to your project with just a few lines of code.
The easiest way is to setup Auth.js with an [OAuth](https://en.wikipedia.org/wiki/OAuth) provider. In this tutorial we'll be setting Auth.js in a **Next.js app** to be able to login with **Github**.
<Callout type="info">
Auth.js comes with a long list of [built-in providers](/reference/providers/oauth-builtin) (Google, Facebook, Twitter, etc...) you can also integrate it with your own OAuth service easily by [building a custom provider](/guides/providers/custom-provider). Auth.js can integrate as well with other frameworks like SvelteKit, SolidStart and Gatsby.
</Callout>
## 1. Configuring Auth.js
### Creating the server config
To add Auth.js to a [**Next.js**](https://nextjs.org/) project, create the following [API route](https://nextjs.org/docs/api-routes/introduction):
```
pages/api/auth/[...nextauth].ts
```
This route will contain the **dynamic route handler** for Auth.js which describes your global auth configuration:
```ts title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
export default NextAuth({
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
})
```
Behind the scenes this creates all the relevant OAuth API routes within `/api/auth/*` so that auth API requests to:
- `/api/auth/callback`
- `/api/auth/signIn`
- `/api/auth/signOut`
- etc...
can be handled by Auth.js. In this way, Auth.js stays in charge of handling the whole authentication request/response flow of your application for you.
You may notice there are some environment variables in the code example above. `GITHUB_ID` and `GITHUB_SECRET` are provided by the OAuth provider (in this case **Github**) see ["Configuring OAuth Provider"](/getting-started/oauth-tutorial#2-configuring-oauth-provider) section on how to get those.
`NEXTAUTH_SECRET` is a random string used by the library to encrypt tokens and email verification hashes, and **it's mandatory to keep things secure**! 🔥 🔐 . You can use:
```
$ openssl rand -base64 32
```
or https://generate-secret.vercel.app/32 to generate a random value for it.
<Callout type="info">
Auth.js is extremely customizable, [our guides section](/guides/overview) will teach you how you can set it up to handle auth in different ways. All the possible configuration options are [listed here](/reference/configuration/auth-config).
</Callout>
### Exposing the session via provider
To be able to use `useSession` first you'll need to expose the session context, [`<SessionProvider />`](/reference/react/#sessionprovider), at the top level of your application:
```ts title="pages/_app.ts"
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
```
Instances of `useSession` (more on it in the next section) will then have access to the session data and status. The `<SessionProvider />` also takes care of keeping the session updated and synced between browser tabs and windows. 💪🏽
<Callout>
Check our [client docs](/reference/react/) to learn all the available options for handling sessions on the browser.
</Callout>
### Consuming the session via hooks
Auth.js exposes a [`useSession()`](/reference/react/#usesession) React Hook so that you can easily check if someone is signed in:
```ts title="pages/overview.tsx"
import { useSession, signIn, signOut } from "next-auth/react"
export default function CamperVanPage() {
const { data: session, status } = useSession()
const userEmail = session?.user.email;
if (status === "loading") {
return <p>Hang on there...</p>
}
if (status === "authenticated") {
return (
<>
<p>Signed in as {userEmail}</p>
<button onClick={() => signOut()}>Sign out</button>
<img src="https://cdn.pixabay.com/photo/2017/08/11/19/36/vw-2632486_1280.png" />
</>
)
}
return (
<>
<p>Not signed in.</p>
<button onClick={() => signIn()}>Sign in</button>
</>
)
}
```
You can use the `useSession` hook from anywhere in your application (e.g. in a header component). Behind the scenes, the hook will connect to the `<SessionProvider />` to read the current user session.
### Protecting API Routes
Protecting your custom API Routes (.i.e not allowing a resource to be accessed in case the user is not logged in) is easy! You can use [`getSession()`](/reference/utilities/#getsession) to know whether a session exists or not:
```ts title="pages/api/movies/list.ts"
import { getSession } from "next-auth/react"
export default async function listMovies(req, res) {
const session = await getSession({ req })
if (session) {
res.send({
movies: [
{ title: "Alien vs Predator", id: 1 },
{ title: "Reservoir Dogs", id: 2 },
],
})
} else {
res.send({
error: "You must sign in to view movies.",
})
}
}
```
## 2. Configuring OAuth Provider
Ok, we have our Next.js app setup with NextAuth, however, if you run the app right now, it won't work as we haven't configured our OAuth provider (**Github**) yet.
<Callout type="info">
When using OAuth you're asking for a third-party service (in this case Github, although it could be Google, Twitter, etc...) to handle user authentication for your app.
</Callout>
We need to register our new Next.js app in Github, so that when Auth.js forwards the authorization requests to it, Github can recognize your application and prompt the user to sign in.
<Image src={creatingOauthAppImg} />
Log in into **Github**, go to `Settings / Developers / OAuth Apps` and click on "New OAuth App".
Next you'll be presented with a screen to add details about your new application. Fill in the required fields, but pay extra attention to the **Authorization Callback URL** one:
<Image src={addingCallbackUrlImg} />
The callback URL we insert should have the following pattern:
```
[origin]/api/auth/callback/[provider]
```
In this case, given we want to try our authentication working locally on our machine and we're using **Github** as our OAuth provider, it'll be:
```
http://localhost:3000/api/auth/callback/github
```
<Callout type="info">
Auth.js will already magically create this API endpoint for you when we start the application later. Note that because we're using Next.js, locally it starts our server on the port `3000`, hence the origin is `http://localhost:3000`.
</Callout>
Next you'll be presented with the following screen which presents all the configuration for your new OAuth app. For now, let's we need two things from it: the **Client ID** and **Client Secret** for our new OAuth app:
<Image src={gettingClientIdSecretImg} />
The Client ID is always there, a public identifier of your OAuth application within Github. Click on the **Generate a new client Secret** button and should be presented with a new string (which is just a randomized string).
<Callout type="warning">
🔥 Keep both your Client ID and Client Secret secure and never expose them to the public or shared with people outside your organization. With tem a malicious actor could hijack your application and cause you and your user serious problems!
</Callout>
Now let's copy both the Client ID and Client Secret and paste them in an environment file in the root of your project like so:
```title=".env.local"
GITHUB_ID=12345
GITHUB_SECRET=67890
```
Cool! We have finished the configuring our OAuth provider, now let's wire all together so we can finally see authentication working in our app!
<Callout type="info">
As noted previously, Auth.js has built-in support for multiple OAuth providers, <a href="">here the full list</a>. You can also easily build your own in case the provider you need is not on the list.
Note that, for each provider, the configuration process will be similar to what we just did:
1. Log in to the provider
2. Create create your OAuth application within it
3. Set the callback URL
4. Get the Client ID and Generate a Client Secret
</Callout>
## 3. Wiring all together
Finally, we just need to reference our **Client ID** and **Client Secret** we just generated in the previous in our Auth.js config. In this way the library will be able to use them when forwarding users to Github, and Github will be able to recognize the request as generated from our application:
```ts title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
export default NextAuth({
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
})
```
Great! We're now ready to run our application locally. Start the Next.js app by running on your terminal the following command and navigating to [`http://localhost:3000`](http://localhost:3000):
```
$ npm run next dev
```
You should see the following page:
<Image src={startAppAndSignInImg} />
Click on "Sign in" and then on "Sign in with Github": Auth.js will redirect you to Github, and Github will recognize our app [that we just registered](#2-configuring-oauth-provider) and ask the user (in this case you) to enter its credentials to proceed:
<Image src={githubAuthCredentials} />
Once inserted and correct, Github will redirect the user to our app and Auth.js will take care of any further calls with Github to get access to the user profile and start a user sessions safely in the background:
<Image src={nextAuthUserLoggedIn} />
Great! We have completed the whole E2E authentication flow setup so that users can login in our application through Github!
<Callout type="info">
You can create your own Sign In page instead of using the default one from Auth.js. You can learn how to do so in our dedicated guide for it.
</Callout>
## 4. Deploying to production
### Configuring different environments
It's normal to test your application under different environments. Usually you'll have a development environment (when you run the application locally in your machine), a staging environment (for teams members to try the application) and a production environment.
For each environment, you're going to need to create an OAuth application in your provider respectively, as [we did previously](#2-configuring-oauth-provider), and point the **callback URL** to it.
For instance in the previous section, we pointed the callback URL to:
```
http://localhost:3000/api/auth/callback/github
```
as we wanted to test our application in the development environment.
If we were to deploy our app to production, we would need to create again a new **OAuth App** in Github (calling it something like "Van life prod") and point the **callback URL** to our production domain:
```
https://example.com/api/auth/callback/github
```
Finally, we would need just to point the environment variables we set ( `GITHUB_ID` and `GITHUB_SECRET` ) to the credentials of the OAuth app we want our application to run against.
### Setting up `NEXTAUTH_URL`
When deploying your site, **you need to set** the `NEXTAUTH_URL` environment variable to the canonical URL of your website:
```
NEXTAUTH_URL=https://example.com
```
<Callout type="warning">
In production, this needs to be set as an environment variable on the service you use to deploy your app.
To set environment variables on Vercel, you can use the [dashboard](https://vercel.com/dashboard) or the `vercel env pull` [command](https://vercel.com/docs/build-step#development-environment-variables).
</Callout>
For more information please check out our [deployment page](/guides/basics/deployment).

View File

@@ -0,0 +1,30 @@
---
title: Security
---
import { Callout } from 'nextra-theme-docs'
## Reporting a Vulnerability
Auth.js practices responsible disclosure.
We request that you contact us directly to report serious issues that might impact the security of sites using Auth.js.
If you contact us regarding a serious issue:
- We will endeavor to get back to you within 72 hours.
- We will aim to publish a fix within 30 days.
- We will disclose the issue (and credit you, with your consent) once a fix to resolve the issue has been released.
- If 90 days has elapsed and we still don't have a fix, we will disclose the issue publicly.
The best way to report an issue is by contacting us via email at info@balazsorban.com or me@iaincollins.com and yo@ndo.dev, or raise a public issue requesting someone get in touch with you via whatever means you prefer for more details. (Please do not disclose sensitive details publicly at this stage.)
<Callout>
For less serious issues (e.g. RFC compliance for unsupported flows or potential issues that may cause a problem in the future) it is appropriate to make these public as bug reports or feature requests or to raise a question to open a discussion around them.
</Callout>
## Supported Versions
Security updates are only released for the current version.
Old releases are not maintained and do not receive updates.

View File

@@ -0,0 +1,164 @@
---
title: TypeScript
---
import { Callout } from 'nextra-theme-docs'
Auth.js has its own type definitions to use in your TypeScript projects safely. Even if you don't use TypeScript, IDEs like VSCode will pick this up to provide you with a better developer experience. While you are typing, you will get suggestions about what certain objects/functions look like, and sometimes links to documentation, examples, and other valuable resources.
Check out the example repository showcasing how to use `next-auth` on a Next.js application with TypeScript:
https://github.com/nextauthjs/next-auth-typescript-example
---
## Adapters
If you're writing your own custom Adapter, you can take advantage of the types to make sure your implementation conforms to what's expected:
```ts
import type { Adapter } from "next-auth/adapters"
function MyAdapter(): Adapter {
return {
// your adapter methods here
}
}
```
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
/** @return { import("next-auth/adapters").Adapter } */
function MyAdapter() {
return {
// your adapter methods here
}
}
```
<Callout>
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.
</Callout>
## Module Augmentation
`next-auth` comes with certain types/interfaces that are shared across submodules. Good examples are `Session` and `JWT`. Ideally, you should only need to create these types at a single place, and TS should pick them up in every location where they are referenced. Luckily, Module Augmentation is exactly that, which can do this for us. Define your shared interfaces in a single place, and get type-safety across your application when using `next-auth` (or one of its submodules).
### Main module
Let's look at `Session`:
```ts title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
export default NextAuth({
callbacks: {
session({ session, token, user }) {
return session // The return type will match the one returned in `useSession()`
},
},
})
```
```ts title="pages/index.ts"
import { useSession } from "next-auth/react"
export default function IndexPage() {
// `session` will match the returned value of `callbacks.session()` from `NextAuth()`
const { data: session } = useSession()
return (
// Your component
)
}
```
To extend/augment this type, create a `types/next-auth.d.ts` file in your project:
```ts title="types/next-auth.d.ts"
import NextAuth from "next-auth"
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's postal address. */
address: string
}
}
}
```
#### Extend default interface properties
By default, TypeScript will merge new interface properties and overwrite existing ones. In this case, the default session user properties will be overwritten, with the new one defined above.
If you want to keep the default session user properties, you need to add them back into the newly declared interface:
```ts title="types/next-auth.d.ts"
import NextAuth, { DefaultSession } from "next-auth"
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's postal address. */
address: string
} & DefaultSession["user"]
}
}
```
#### Popular interfaces to augment
Although you can augment almost anything, here are some of the more common interfaces that you might want to override in the `next-auth` module:
```ts
/**
* The shape of the user object returned in the OAuth providers' `profile` callback,
* or the second parameter of the `session` callback, when using a database.
*/
interface User {}
/**
* Usually contains information about the provider being used
* and also extends `TokenSet`, which is different tokens returned by OAuth Providers.
*/
interface Account {}
/** The OAuth profile returned from your provider */
interface Profile {}
```
Make sure that the `types` folder is added to [`typeRoots`](https://www.typescriptlang.org/tsconfig/#typeRoots) in your project's `tsconfig.json` file.
### Submodules
The `JWT` interface can be found in the `next-auth/jwt` submodule:
```ts title="types/next-auth.d.ts"
import { JWT } from "next-auth/jwt"
declare module "next-auth/jwt" {
/** Returned by the `jwt` callback and `getToken`, when using JWT sessions */
interface JWT {
/** OpenID ID Token */
idToken?: string
}
}
```
### Useful links
1. [TypeScript documentation: Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
2. [Digital Ocean: Module Augmentation in TypeScript](https://www.digitalocean.com/community/tutorials/typescript-module-augmentation)
## Contributing
Contributions of any kind are always welcome, especially for TypeScript. Please keep in mind that we are a small team working on this project in our free time. We will try our best to give support, but if you think you have a solution for a problem, please open a PR!
<Callout>
When contributing to TypeScript, if the actual JavaScript user API does not change in a breaking manner, we reserve the right to push any TypeScript change in a minor release. This ensures that we can keep on a faster release cycle.
</Callout>

View File

@@ -0,0 +1,13 @@
{
"index": "Introduction",
"basics": "Basics",
"adapters": "Adapters",
"providers": "Providers",
"testing": "Testing",
"corporate-proxies": "Proxies",
"other": "Other",
"resources": "Community Resources",
"img": {
"display": "hidden"
}
}

View File

@@ -0,0 +1,4 @@
{
"creating-a-database-adapter": "Create a Database Adapter",
"using-a-database-adapter": "Using a Database Adapter"
}

View File

@@ -0,0 +1,90 @@
---
title: Creating a database adapter
---
Using a custom adapter you can connect to any database back-end or even several different databases. Official adapters created and maintained by our community can be found in the [adapters](https://github.com/nextauthjs/next-auth/tree/main/packages) packages. Feel free to add a custom adapter from your project to the repository, or even become a maintainer of a certain adapter. Custom adapters can still be created and used in a project without being added to the repository.
## How to create an adapter
For more information about the data these methods need to manage see [models](/reference/adapters/models).
_See the code below for practical example._
### Example code
```ts
/** @return { import("next-auth/adapters").Adapter } */
export default function MyAdapter(client, options = {}) {
return {
async createUser(user) {
return
},
async getUser(id) {
return
},
async getUserByEmail(email) {
return
},
async getUserByAccount({ providerAccountId, provider }) {
return
},
async updateUser(user) {
return
},
async deleteUser(userId) {
return
},
async linkAccount(account) {
return
},
async unlinkAccount({ providerAccountId, provider }) {
return
},
async createSession({ sessionToken, userId, expires }) {
return
},
async getSessionAndUser(sessionToken) {
return
},
async updateSession({ sessionToken }) {
return
},
async deleteSession(sessionToken) {
return
},
async createVerificationToken({ identifier, expires, token }) {
return
},
async useVerificationToken({ identifier, token }) {
return
},
}
}
```
### Required methods
These methods are required for all sign in flows:
- `createUser`
- `getUser`
- `getUserByEmail`
- `getUserByAccount`
- `linkAccount`
- `createSession`
- `getSessionAndUser`
- `updateSession`
- `deleteSession`
- `updateUser`
These methods are required to support email / passwordless sign in:
- `createVerificationToken`
- `useVerificationToken`
### Unimplemented methods
These methods will be required in a future release, but are not yet invoked:
- `deleteUser`
- `unlinkAccount`

View File

@@ -0,0 +1,15 @@
---
title: Using a Database Adapter
---
import { Callout } from 'nextra-theme-docs'
An **Adapter** in Auth.js connects your application to whatever database or backend system you want to use to store data for users, their accounts, sessions, etc. Adapters are optional, unless you need to persist user information in your own database, or you want to implement certain flows. The [Email Provider](/getting-started/email-tutorial) requires an adapter to be able to save [Verification Tokens](/reference/adapters/models#verification-token).
<Callout>
When using a database, you can still use JWT for session handling for fast access. See the [`session.strategy`](/reference/configuration/auth-config#session) option. Read about the trade-offs of JWT in the [FAQ](/concepts/faq#json-web-tokens).
</Callout>
We have a list of official adapters that are distributed as their own packages under the `@next-auth/{name}-adapter` namespace. Their source code is available in their various adapters package directories at [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth/tree/main/packages):
- [All available adapters](/reference/adapters/overview)

View File

@@ -0,0 +1,11 @@
{
"initialization": "Initialization",
"callbacks": "Callbacks",
"events": "Events",
"pages": "Pages",
"securing-pages-and-api-routes": "Securing Pages and API Routes",
"overriding-jwt": "Overriding JWT",
"refresh-token-rotation": "Refresh Token Rotation",
"role-based-login-strategy": "Role-Based Access Control",
"deployment": "Deployment"
}

View File

@@ -0,0 +1,170 @@
---
title: Callbacks
---
import { Callout } from "nextra-theme-docs"
Callbacks are **asynchronous** functions you can use to control what happens when an action is performed.
Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.
<Callout>
If you want to pass data such as an Access Token or User ID to the browser
when using JSON Web Tokens, you can persist the data in the token when the
`jwt` callback is called, then pass the data through to the browser in the
`session` callback.
</Callout>
You can specify a handler for any of the callbacks below.
```js title="pages/api/auth/[...nextauth].js"s
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
return true
},
async redirect({ url, baseUrl }) {
return baseUrl
},
async session({ session, user, token }) {
return session
},
async jwt({ token, user, account, profile, isNewUser }) {
return token
}
}
```
The documentation below shows how to implement each callback, their default behavior and an example of what the response for each callback should be. Note that configuration options and authentication providers you are using can impact the values passed to the callbacks.
## Sign in callback
Use the `signIn()` callback to control if a user is allowed to sign in.
```js title="pages/api/auth/[...nextauth].js"
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
const isAllowedToSignIn = true
if (isAllowedToSignIn) {
return true
} else {
// Return false to display a default error message
return false
// Or you can return a URL to redirect to:
// return '/unauthorized'
}
}
}
```
- When using the **Email Provider** the `signIn()` callback is triggered both when the user makes a **Verification Request** (before they are sent an email with a link that will allow them to sign in) and again _after_ they activate the link in the sign-in email.
Email accounts do not have profiles in the same way OAuth accounts do. On the first call during email sign in the `email` object will include a property `verificationRequest: true` to indicate it is being triggered in the verification request flow. When the callback is invoked _after_ a user has clicked on a sign-in link, this property will not be present.
You can check for the `verificationRequest` property to avoid sending emails to addresses or domains on a blocklist (or to only explicitly generate them for email address in an allow list).
* When using the **Credentials Provider** the `user` object is the response returned from the `authorize` callback and the `profile` object is the raw body of the `HTTP POST` submission.
<Callout>
When using Auth.js with a database, the User object will be either a user object from the database (including the User ID) if the user has signed in before or a simpler prototype user object (i.e. name, email, image) for users who have not signed in before.
When using Auth.js without a database, the user object will always be a prototype user object, with information extracted from the profile.
</Callout>
<Callout>
Redirects returned by this callback cancel the authentication flow. Only redirect to error pages that, for example, tell the user why they're not allowed to sign in.
To redirect to a page after a successful sign in, please use [the `callbackUrl` option](/reference/utilities/#specifying-a-callbackurl) or [the redirect callback](/reference/configuration/auth-config#callbacks).
</Callout>
## Redirect callback
The redirect callback is called anytime the user is redirected to a callback URL (e.g. on sign in or sign out).
By default only URLs on the same URL as the site are allowed, you can use the redirect callback to customize that behavior.
The default redirect callback looks like this:
```js title="pages/api/auth/[...nextauth].js"
callbacks: {
async redirect({ url, baseUrl }) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url
return baseUrl
}
}
```
<Callout>
The redirect callback may be invoked more than once in the same flow.
</Callout>
## JWT callback
This callback is called whenever a JSON Web Token is created (i.e. at sign
in) or updated (i.e whenever a session is accessed in the client). The returned value will be [encrypted](/reference/configuration/auth-config#jwt), and it is stored in a cookie.
Requests to `/api/auth/signin`, `/api/auth/session` and calls to `getSession()`, `unstable_getServerSession()`, `useSession()` will invoke this function, but only if you are using a [JWT session](/reference/configuration/auth-config#session). This method is not invoked when you persist sessions in a database.
- As with database persisted session expiry times, token expiry time is extended whenever a session is active.
- The arguments _user_, _account_, _profile_ and _isNewUser_ are only passed the first time this callback is called on a new session, after the user signs in. In subsequent calls, only `token` will be available.
The contents _user_, _account_, _profile_ and _isNewUser_ will vary depending on the provider and on if you are using a database or not. You can persist data such as User ID, OAuth Access Token in this token. To make it available in the browser, check out the [`session()` callback](#session-callback) as well.
```js title="pages/api/auth/[...nextauth].js"
callbacks: {
async jwt({ token, account }) {
// Persist the OAuth access_token to the token right after signin
if (account) {
token.accessToken = account.access_token
}
return token
}
}
```
<Callout>
Use an if branch to check for the existence of parameters (apart from
`token`). If they exist, this means that the callback is being invoked for the
first time (i.e. the user is being signed in). This is a good place to persist
additional data like an `access_token` in the JWT. Subsequent invocations will
only contain the `token` parameter.
</Callout>
## Session callback
The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token through the `jwt()` callback, you have to explicitly forward it here to make it available to the client.
e.g. `getSession()`, `useSession()`, `/api/auth/session`
- When using database sessions, the User object is passed as an argument.
- When using JSON Web Tokens for sessions, the JWT payload is provided instead.
```js title="pages/api/auth/[...nextauth].js"
callbacks: {
async session({ session, token, user }) {
// Send properties to the client, like an access_token from a provider.
session.accessToken = token.accessToken
return session
}
}
```
<Callout>
When using JSON Web Tokens the `jwt()` callback is invoked before the
`session()` callback, so anything you add to the JSON Web Token will be
immediately available in the session callback, like for example an
`access_token` from a provider.
</Callout>
<Callout type="warning">
The session object is not persisted server side, even when using database sessions - only data such as the session token, the user, and the expiry time is stored in the session table.
If you need to persist session data server side, you can use the `accessToken` returned for the session as a key - and connect to the database in the `session()` callback to access it. Session `accessToken` values do not rotate and are valid as long as the session is valid.
If using JSON Web Tokens instead of database sessions, you should use the User ID or a unique key stored in the token (you will need to generate a key for this yourself on sign in, as access tokens for sessions are not generated when using JSON Web Tokens).
</Callout>

View File

@@ -0,0 +1,94 @@
---
title: Deployment
---
Deploying Auth.js only requires a few steps. It can be run anywhere a Next.js application can. Therefore, in a default configuration using only JWT session strategy, i.e. without a database, you will only need these few things in addition to your application:
1. Auth.js environment variables
- `NEXTAUTH_SECRET`
- `NEXTAUTH_URL`
2. Auth.js API Route and its configuration (`/pages/api/auth/[...nextauth].js`).
- OAuth Provider `clientId` / `clientSecret`
Deploying a modern JavaScript application using Auth.js consists of making sure your environment variables are set correctly as well as the configuration in the Auth.js API route is setup, as well as any configuration (like Callback URLs, etc.) are correctly done in your OAuth provider(s) themselves.
See below for more detailed provider settings.
## Vercel
1. Make sure to expose the Vercel [System Environment Variables](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables) in your project settings.
2. Create a `NEXTAUTH_SECRET` environment variable for all environments.
a. You can use `openssl rand -base64 32` or https://generate-secret.vercel.app/32 to generate a random value.
b. You **do not** need the `NEXTAUTH_URL` environment variable in Vercel.
3. Add your provider's client ID and client secret to environment variables. _(Skip this step if not using an [OAuth Provider](/reference/providers/index))_
4. Deploy!
Example repository: https://github.com/nextauthjs/next-auth-example
A few notes about deploying to Vercel. The environment variables are read server-side, so you do not need to prefix them with `NEXT_PUBLIC_`. When deploying here, you do not need to explicitly set the `NEXTAUTH_URL` environment variable. With other providers **you will** need to also set this environment variable.
### Securing a preview deployment
Securing a preview deployment (with an OAuth provider) comes with some critical obstacles. Most OAuth providers only allow a single redirect/callback URL, or at least a set of full static URLs. Meaning you cannot set the value before publishing the site and you cannot use wildcard subdomains in the callback URL settings of your OAuth provider. Here are a few ways you can still use Auth.js to secure your Preview Deployments.
#### Using the Credentials Provider
You could check in your `/pages/api/auth/[...nextauth].js` API route / configuration file to see if you're currently in a Vercel preview environment, and if so, enable a simple "credential provider", meaning username/password. Vercel offers a few built-in [system environment variables](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables) which you could check against, like `VERCEL_ENV`. This would allow you to use this basic, for testing only, authentication strategy in your preview deployments.
Some things to be aware of here, include:
- Do not let this potential testing-only user have access to any critical data
- If possible, maybe do not even connect this preview deployment to your production database
##### Example
```js title="/pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import CredentialsProvider from "next-auth/providers/credentials"
export default NextAuth({
providers: [
process.env.VERCEL_ENV === "preview"
? CredentialsProvider({
name: "Credentials",
credentials: {
username: {
label: "Username",
type: "text",
placeholder: "jsmith",
},
password: { label: "Password", type: "password" },
},
async authorize() {
return {
id: 1,
name: "J Smith",
email: "jsmith@example.com",
image: "https://i.pravatar.cc/150?u=jsmith@example.com",
}
},
})
: GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
})
```
#### Using the branch based preview URL
Preview deployments at Vercel are often available via multiple URLs. For example, PR's merged to `master` or `main`, will be available the commit and PR specific preview URLs, but also the branch specific preview URLs. This branch specific URL will obviously not change as long as you work with that same branch. Therefore, you could add to your OAuth provider your `{project}-git-main-{user}.vercel.app` preview URL. As this will stay constant for that branch, you can reuse that preview deployment / URL for testing any authentication related deployments.
## Netlify
Netlify is very similar to Vercel in that you can deploy a Next.js project without almost any extra work.
In order to setup Auth.js correctly here, you will want to make sure you add your `NEXTAUTH_SECRET` environment variable in the project settings. If you are using the [Essential Next.js Build Plugin](https://github.com/netlify/netlify-plugin-nextjs) within your project, you **do not** need to set the `NEXTAUTH_URL` environment variable as it is set automatically as part of the build process.
Netlify also exposes some [system environment variables](https://docs.netlify.com/configure-builds/environment-variables/) from which you can check which `NODE_ENV` you are currently in and much more.
After this, just make sure you either have your OAuth provider setup correctly with `clientId` / `clientSecret`'s and callback URLs.

View File

@@ -0,0 +1,66 @@
---
title: Events
---
import { Callout } from 'nextra-theme-docs'
Events are asynchronous functions that do not return a response, they are useful for audit logs / reporting or handling any other side-effects.
You can specify a handler for any of these events below, for debugging or for an audit log.
<Callout>
The execution of your authentication API will be blocked by an `await` on your event handler. If your event handler starts any burdensome work it should not block its own promise on that work.
</Callout>
## Events
### signIn
Sent on a successful sign in.
The message will be an object and contain:
- `user` (from your adapter or from the provider if a `credentials` type provider)
- `account` (from your adapter or the provider)
- `profile` (from the provider, is `undefined` on `credentials` provider, use `user` instead)
- `isNewUser` (whether your adapter had a user for this account already)
### signOut
Sent when the user signs out.
The message object will contain one of these depending on if you use JWT or database persisted sessions:
- `token`: The JWT token for this session.
- `session`: The session object from your adapter that is being ended
### createUser
Sent when the adapter is told to create a new user.
The message object will contain the user.
### updateUser
Sent when the adapter is told to update an existing user. Currently, this is only sent when the user verifies their email address.
The message object will contain the user.
### linkAccount
Sent when an account in a given provider is linked to a user in our user database. For example, when a user signs up with Twitter or when an existing user links their Google account.
The message object will contain:
- `user`: The user object from your adapter.
- `account`: The object returned from the provider.
- `profile`: The object returned from the `profile` callback of the OAuth provider.
### session
Sent at the end of a request for the current session.
The message object will contain one of these depending on if you use JWT or database persisted sessions:
- `token`: The JWT token for this session.
- `session`: The session object from your adapter.

View File

@@ -0,0 +1,124 @@
---
title: Custom Initialization
---
import { Callout } from 'nextra-theme-docs'
In Next.js, you can define an API route that will catch all requests that begin with a certain path. Conveniently, this is called [Catch all API routes](https://nextjs.org/docs/api-routes/dynamic-api-routes#catch-all-api-routes).
When you define a `/pages/api/auth/[...nextauth]` JS/TS file, you instruct Auth.js that every API request beginning with `/api/auth/*` should be handled by the code written in the `[...nextauth]` file.
Depending on your use case, you can initialize Auth.js in two different ways:
## Simple initialization
In most cases, you won't need to worry about what `Auth.js` does, and you will get by just fine with the following initialization:
```ts title="/pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
export default NextAuth({
...
})
```
Here, you only need to pass your [options](/reference/configuration/auth-config) to `NextAuth`, and `NextAuth` does the rest.
This is the preferred initialization in tutorials/other parts of the documentation, as it simplifies the code and reduces potential errors in the authentication flow.
## Advanced initialization
If you have a specific use case and need to make Auth.js do something slightly different than what it is designed for, keep in mind, the `[...nextauth].js` config file is still just **a regular [API Route](https://nextjs.org/docs/api-routes/introduction)** at the end of the day.
That said, you can initialize Auth.js like this:
```ts title="/pages/api/auth/[...nextauth].ts"
import type { NextApiRequest, NextApiResponse } from "next"
import NextAuth from "next-auth"
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
// Do whatever you want here, before the request is passed down to `NextAuth`
return await NextAuth(req, res, {
...
})
}
```
The `...` section will still be your [options](/reference/configuration/auth-config), but you now have the possibility to execute/modify certain things on the request.
You could for example log the request, add headers, read `query` or `body` parameters, whatever you would do in an API route.
<Callout>
Since this is a catch-all route, remember to check what kind of Auth.js "action" is running. Compare the REST API with the `req.query.nextauth` parameter.
For example to execute something on the "callback" action when the request is a POST method, you can check for `req.query.nextauth.includes("callback") && req.method === "POST"`
</Callout>
<Callout>
`NextAuth` will implicitly close the response (by calling `res.end`, `res.send` or similar), so you should not run code **after** `NextAuth` in the function body. Using `return NextAuth` makes sure you don't forget that.
</Callout>
Any variable you create this way will be available in the `NextAuth` options as well, since they are in the same scope.
```ts title="/pages/api/auth/[...nextauth].ts"
import type { NextApiRequest, NextApiResponse } from "next"
import NextAuth from "next-auth"
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
if(req.query.nextauth.includes("callback") && req.method === "POST") {
console.log(
"Handling callback request from my Identity Provider",
req.body
)
}
// Get a custom cookie value from the request
const someCookie = req.cookies["some-custom-cookie"]
return await NextAuth(req, res, {
...
callbacks: {
session({ session, token }) {
// Return a cookie value as part of the session
// This is read when `req.query.nextauth.includes("session") && req.method === "GET"`
session.someCookie = someCookie
return session
}
}
})
}
```
A practical example could be to not show a certain provider on the default sign-in page, but still be able to sign in with it. (The idea is taken from [this discussion](https://github.com/nextauthjs/next-auth/discussions/3133)):
```js title="/pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import GoogleProvider from "next-auth/providers/google"
export default async function auth(req, res) {
const providers = [
CredentialsProvider(...),
GoogleProvider(...),
]
const isDefaultSigninPage = req.method === "GET" && req.query.nextauth.includes("signin")
// Will hide the `GoogleProvider` when you visit `/api/auth/signin`
if (isDefaultSigninPage) providers.pop()
return await NextAuth(req, res, {
providers,
...
})
}
```
For more details on all available actions and which methods are supported, please check out the [REST API documentation](/reference/rest-api) or the appropriate area in [the source code](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/index.ts)
This way of initializing `NextAuth` is very powerful, but should be used sparingly.
<Callout type="warning">
Changing parts of the request that is essential to `NextAuth` to do it's job - like messing with the [default cookies](/reference/configuration/auth-config#cookies) - can have unforeseen consequences, and have the potential to introduce security holes if done incorrectly. Only change those if you understand consequences.
</Callout>

View File

@@ -0,0 +1,32 @@
---
title: Override JWT `encode` and `decode` methods
sidebar_label: Custom JWT encoding
---
import { Callout } from "nextra-theme-docs"
<Callout type="warning">
If you use middleware to protect routes, make sure the same method is also set in the [`_middleware.ts` options](/reference/nextjs/#custom-jwt-decode-method)
</Callout>
Auth.js uses encrypted JSON Web Tokens ([JWE](https://datatracker.ietf.org/doc/html/rfc7516)) by default. Unless you have a good reason, we recommend keeping this behaviour. Although you can override this using the `encode` and `decode` methods. Both methods must be defined at the same time.
```js
jwt: {
async encode(params: {
token: JWT
secret: string
maxAge: number
}): Promise<string> {
// return a custom encoded JWT string
return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
},
async decode(params: {
token: string
secret: string
}): Promise<JWT | null> {
// return a `JWT` object, or `null` if decoding failed
return {}
},
}
```

View File

@@ -0,0 +1,183 @@
---
title: Pages
---
import { Callout } from 'nextra-theme-docs'
Auth.js automatically creates simple, unbranded authentication pages for handling Sign in, Sign out, Email Verification and displaying error messages.
The options displayed on the sign-up page are automatically generated based on the providers specified in the options passed to Auth.js.
To add a custom login page, you can use the `pages` option:
```javascript title="pages/api/auth/[...nextauth].js"
...
pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error', // Error code passed in query string as ?error=
verifyRequest: '/auth/verify-request', // (used for check email message)
newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest)
}
...
```
<Callout>
When using this configuration, ensure that these pages actually exist. For example `error: '/auth/error'` refers to a page file at `pages/auth/error.js`.
</Callout>
## Error codes
We purposefully restrict the returned error codes for increased security.
### Error page
The following errors are passed as error query parameters to the default or overridden error page:
- **Configuration**: There is a problem with the server configuration. Check if your [options](/reference/configuration/auth-config) are correct.
- **AccessDenied**: Usually occurs, when you restricted access through the [`signIn` callback](/guides/basics/callbacks#sign-in-callback), or [`redirect` callback](/guides/basics/callbacks#redirect-callback)
- **Verification**: Related to the Email provider. The token has expired or has already been used
- **Default**: Catch all, will apply, if none of the above matched
Example: `/auth/error?error=Configuration`
### Sign-in page
The following errors are passed as error query parameters to the default or overridden sign-in page:
- **OAuthSignin**: Error in constructing an authorization URL ([1](https://github.com/nextauthjs/next-auth/blob/457952bb5abf08b09861b0e5da403080cd5525be/src/server/lib/signin/oauth.js), [2](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/lib/oauth/pkce-handler.ts), [3](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/lib/oauth/state-handler.ts)),
- **OAuthCallback**: Error in handling the response ([1](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/lib/oauth/callback.ts), [2](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/lib/oauth/pkce-handler.ts), [3](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/lib/oauth/state-handler.ts)) from an OAuth provider.
- **OAuthCreateAccount**: Could not create OAuth provider user in the database.
- **EmailCreateAccount**: Could not create email provider user in the database.
- **Callback**: Error in the [OAuth callback handler route](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/routes/callback.ts)
- **OAuthAccountNotLinked**: If the email on the account is already linked, but not with this OAuth account
- **EmailSignin**: Sending the e-mail with the verification token failed
- **CredentialsSignin**: The `authorize` callback returned `null` in the [Credentials provider](/getting-started/credentials-tutorial). We don't recommend providing information about which part of the credentials were wrong, as it might be abused by malicious hackers.
- **SessionRequired**: The content of this page requires you to be signed in at all times. See [useSession](/reference/react/#usesession) for configuration.
- **Default**: Catch all, will apply, if none of the above matched
Example: `/auth/signin?error=Default`
## Theming
By default, the built-in pages will follow the system theme, utilizing the [`prefer-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) Media Query. You can override this to always use a dark or light theme, through the [`theme.colorScheme` option](/reference/configuration/auth-config#theme).
In addition, you can define the background color and text color of the button with the `theme.brandColor` and `theme.buttonText` options. You can also define a URL to a logo in `theme.logo` which will be rendered at the top of the card.
#### Sign In
![Customized Signin Page](/img/pages_signin.png)
#### Sign Out
![Customized Signout Page](/img/pages_signout.png)
## Examples
### OAuth Sign in
In order to get the available authentication providers and the URLs to use for them, you can make a request to the API endpoint `/api/auth/providers`:
```jsx title="pages/auth/signin.js"
import { getProviders, signIn } from "next-auth/react"
export default function SignIn({ providers }) {
return (
<>
{Object.values(providers).map((provider) => (
<div key={provider.name}>
<button onClick={() => signIn(provider.id)}>
Sign in with {provider.name}
</button>
</div>
))}
</>
)
}
export async function getServerSideProps(context) {
const providers = await getProviders()
return {
props: { providers },
}
}
```
There is another, more fully styled example signin page available [here](https://github.com/ndom91/next-auth-example-sign-in-page).
### Email Sign in
If you create a custom sign in form for email sign in, you will need to submit both fields for the **email** address and **csrfToken** from **/api/auth/csrf** in a POST request to **/api/auth/signin/email**.
```jsx title="pages/auth/email-signin.js"
import { getCsrfToken } from "next-auth/react"
export default function SignIn({ csrfToken }) {
return (
<form method="post" action="/api/auth/signin/email">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
<label>
Email address
<input type="email" id="email" name="email" />
</label>
<button type="submit">Sign in with Email</button>
</form>
)
}
export async function getServerSideProps(context) {
const csrfToken = await getCsrfToken(context)
return {
props: { csrfToken },
}
}
```
You can also use the `signIn()` function which will handle obtaining the CSRF token for you:
```js
signIn("email", { email: "jsmith@example.com" })
```
### Credentials Sign in
If you create a sign in form for credentials based authentication, you will need to pass a **csrfToken** from **/api/auth/csrf** in a `POST` request to **/api/auth/callback/credentials**.
```jsx title="pages/auth/credentials-signin.js"
import { getCsrfToken } from "next-auth/react"
export default function SignIn({ csrfToken }) {
return (
<form method="post" action="/api/auth/callback/credentials">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
<label>
Username
<input name="username" type="text" />
</label>
<label>
Password
<input name="password" type="password" />
</label>
<button type="submit">Sign in</button>
</form>
)
}
export async function getServerSideProps(context) {
return {
props: {
csrfToken: await getCsrfToken(context),
},
}
}
```
You can also use the `signIn()` function which will handle obtaining the CSRF token for you:
```js
signIn("credentials", { username: "jsmith", password: "1234" })
```
<Callout type="info">
Remember to put any custom pages in a folder outside **/pages/api** which is reserved for API code. As per the examples above, a location convention suggestion is `pages/auth/...`.
</Callout>

View File

@@ -0,0 +1,229 @@
---
title: Refresh token rotation
---
import { Callout } from "nextra-theme-docs"
Refresh token rotation is the practice of updating an `access_token` on behalf of the user, without requiring interaction (eg.: re-sign in). `access_token`s are usually issued for a limited time. After they expire, the service verifying them will ignore the value. Instead of asking the user to sign in again to obtain a new `access_token`, certain providers support exchanging a `refresh_token` for a new `access_token`, renewing the expiry time. Let's see how this can be achieved.
<Callout>
Our goal is to add zero-config support for built-in providers eventually. Let
us know if you would like to help.
</Callout>
## Implementation
First, make sure that the provider you want to use supports `refresh_token`'s. Check out [The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749#section-6) spec for more details.
### Server Side
Depending on the session strategy, `refresh_token` can be persisted either in a database, or in a cookie, in an encrypted JWT.
<Callout type="info">
Using a JWT to store the `refresh_token` is less secure than saving it in a
database, and you need to evaluate based on your requirements which strategy
you choose.
</Callout>
#### JWT strategy
Using the [jwt](../../reference/03-core/interfaces/types.CallbacksOptions.md#jwt) and [session](../../reference/03-core/interfaces/types.CallbacksOptions.md#session) callbacks, we can persist OAuth tokens and refresh them when they expire.
Below is a sample implementation using Google's Identity Provider. Please note that the OAuth 2.0 request in the `refreshAccessToken()` function will vary between different providers, but the core logic should remain similar.
```ts
import { Auth } from "@auth/core"
import { type TokenSet } from "@auth/core/types"
import Google from "@auth/core/providers/google"
export default Auth(new Request("https://example.com"), {
providers: [
Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
authorization: { params: { access_type: "offline", prompt: "consent" } },
}),
],
callbacks: {
async jwt({ token, account }) {
if (account) {
// Save the access token and refresh token in the JWT on the initial login
return {
access_token: account.access_token,
expires_at: Date.now() + account.expires_in * 1000,
refresh_token: account.refresh_token,
}
} else if (Date.now() < token.expires_at) {
// If the access token has not expired yet, return it
return token
} else {
// If the access token has expired, try to refresh it
try {
// https://accounts.google.com/.well-known/openid-configuration
// We need the `token_endpoint`.
const response = await fetch("https://oauth2.googleapis.com/token", {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: process.env.GOOGLE_ID,
client_secret: process.env.GOOGLE_SECRET,
grant_type: "refresh_token",
refresh_token: token.refresh_token,
}),
method: "POST",
})
const tokens: TokenSet = await response.json()
if (!response.ok) throw tokens
return {
...token, // Keep the previous token properties
access_token: tokens.access_token,
expires_at: Date.now() + tokens.expires_in * 1000,
// Fall back to old refresh token, but note that
// many providers may only allow using a refresh token once.
refresh_token: tokens.refresh_token ?? token.refresh_token,
}
} catch (error) {
console.error("Error refreshing access token", error)
// The error property will be used client-side to handle the refresh token error
return { ...token, error: "RefreshAccessTokenError" as const }
}
}
},
async session({ session, token }) {
session.error = token.error
return session
},
},
})
declare module "@auth/core/types" {
interface Session {
error?: "RefreshAccessTokenError"
}
}
declare module "@auth/core/jwt" {
interface JWT {
access_token: string
expires_at: number
refresh_token: string
error?: "RefreshAccessTokenError"
}
}
```
#### Database strategy
Using the database strategy is very similar, but instead of preserving the `access_token` and `refresh_token`, we save it, well, in the database.
```ts
import { Auth } from "@auth/core"
import { type TokenSet } from "@auth/core/types"
import Google from "@auth/core/providers/google"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
export default Auth(new Request("https://example.com"), {
adapter: PrismaAdapter(prisma),
providers: [
Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
authorization: { params: { access_type: "offline", prompt: "consent" } },
}),
],
callbacks: {
async session({ session, user }) {
const [google] = await prisma.account.findMany({
where: { userId: user.id, provider: "google" },
})
if (google.expires_at >= Date.now()) {
// If the access token has expired, try to refresh it
try {
// https://accounts.google.com/.well-known/openid-configuration
// We need the `token_endpoint`.
const response = await fetch("https://oauth2.googleapis.com/token", {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: process.env.GOOGLE_ID,
client_secret: process.env.GOOGLE_SECRET,
grant_type: "refresh_token",
refresh_token: google.refresh_token,
}),
method: "POST",
})
const tokens: TokenSet = await response.json()
if (!response.ok) throw tokens
await prisma.account.update({
data: {
access_token: tokens.access_token,
expires_at: Date.now() + tokens.expires_in * 1000,
refresh_token: tokens.refresh_token ?? google.refresh_token,
},
where: {
provider_providerAccountId: {
provider: "google",
providerAccountId: google.providerAccountId,
},
},
})
} catch (error) {
console.error("Error refreshing access token", error)
// The error property will be used client-side to handle the refresh token error
session.error = "RefreshAccessTokenError"
}
}
return session
},
},
})
declare module "@auth/core/types" {
interface Session {
error?: "RefreshAccessTokenError"
}
}
declare module "@auth/core/jwt" {
interface JWT {
access_token: string
expires_at: number
refresh_token: string
error?: "RefreshAccessTokenError"
}
}
```
### Client Side
The `RefreshAccessTokenError` error that is caught in the `refreshAccessToken()` method is passed to the client. This means that you can direct the user to the sign-in flow if we cannot refresh their token.
We can handle this functionality as a side effect:
```js title="pages/home.js"
import { signIn, useSession } from "next-auth/react";
import { useEffect } from "react";
const HomePage() {
const { data: session } = useSession();
useEffect(() => {
if (session?.error === "RefreshAccessTokenError") {
signIn(); // Force sign in to hopefully resolve error
}
}, [session]);
return (...)
}
```
## Source Code
A working example can be accessed [here](https://github.com/nextauthjs/next-auth-refresh-token-example).

View File

@@ -0,0 +1,64 @@
---
title: Role based logins
---
To add role based authentication to your application, you must do three things.
1. Update your database schema
2. Add the `role` to the session object
3. Check for `role` in your pages/components
First modify the `user` table and add a `role` column with the type of `String?`.
Below is an example Prisma schema file.
```javascript title="/prisma/schema.prisma"
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
role String? // New Column
accounts Account[]
sessions Session[]
}
```
Next, implement a custom session callback in the `[...nextauth].js` file, as shown below.
```javascript title="/pages/api/auth/[...nextauth].js"
callbacks: {
async session({ session, token, user }) {
session.user.role = user.role; // Add role value to user object so it is passed along with session
return session;
},
```
Going forward, when using the `getSession` hook, check that `session.user.role` matches the required role. The example below assumes the role `'admin'` is required.
```javascript title="/pages/admin.js"
import { getSession } from "next-auth/react"
export default function Page() {
const session = await getSession({ req })
if (session && session.user.role === "admin") {
return (
<div>
<h1>Admin</h1>
<p>Welcome to the Admin Portal!</p>
</div>
)
} else {
return (
<div>
<h1>You are not authorized to view this page!</h1>
</div>
)
}
}
```
Then it is up to you how you manage your roles, either through direct database access or building your own role update API.

View File

@@ -0,0 +1,169 @@
---
title: Securing Pages & API routes
---
import { Callout } from "nextra-theme-docs"
You can easily protect client and server side rendered pages and API routes with Auth.js.
_You can find working examples of the approaches shown below in the [example project](https://github.com/nextauthjs/next-auth-example/)._
<Callout>
The methods `getSession()` and `getToken()` both return an `object` if a session is valid and `null` if a session is invalid or has expired.
</Callout>
## Securing Pages
### Client Side
If data on a page is fetched using calls to secure API routes - i.e. routes which use `getSession()` or `getToken()` to access the session - you can use the `useSession` React Hook to secure pages.
```js title="pages/client-side-example.js"
import { useSession, getSession } from "next-auth/react"
export default function Page() {
const { data: session, status } = useSession()
if (status === "loading") {
return <p>Loading...</p>
}
if (status === "unauthenticated") {
return <p>Access Denied</p>
}
return (
<>
<h1>Protected Page</h1>
<p>You can view this page because you are signed in.</p>
</>
)
}
```
### Next.js (Middleware)
With Auth.js 4.2.0 and Next.js 12, you can now protect your pages via the middleware pattern more easily. If you would like to protect all pages, you can create a `_middleware.js` file in your root `pages` directory which looks like this.
```js title="/middleware.js"
export { default } from "next-auth/middleware"
```
Otherwise, if you only want to protect a subset of pages, you could put it in a subdirectory as well, for example in `/pages/admin/_middleware.js` would protect all pages under `/admin`.
For the time being, the `withAuth` middleware only supports `"jwt"` as [session strategy](/reference/configuration/auth-config#session).
More details can be found [here](/reference/nextjs/#middleware).
### Server Side
You can protect server side rendered pages using the `unstable_getServerSession` method. This is different from the old `getSession()` method, in that it does not do an extra fetch out over the internet to confirm data from itself, increasing performance significantly.
You need to add this to every server rendered page you want to protect. Be aware, `unstable_getServerSession` takes slightly different arguments than the method it is replacing, `getSession`.
```js title="pages/server-side-example.js"
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"
import { useSession } from "next-auth/react"
export default function Page() {
const { data: session } = useSession()
if (session) {
return (
<>
<h1>Protected Page</h1>
<p>You can view this page because you are signed in.</p>
</>
)
}
return <p>Access Denied</p>
}
export async function getServerSideProps(context) {
return {
props: {
session: await unstable_getServerSession(
context.req,
context.res,
authOptions
),
},
}
}
```
<Callout>
When you supply a `session` prop in `_app.js`, `useSession` won't show a loading state, as it'll already have the session available. In this way, you can provide a more seamless user experience.
```js title="pages/_app.js"
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
```
</Callout>
## Securing API Routes
### Using unstable_getServerSession()
You can protect API routes using the `unstable_getServerSession()` method.
```js title="pages/api/get-session-example.js"
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"
export default async (req, res) => {
const session = await unstable_getServerSession(req, res, authOptions)
if (session) {
// Signed in
console.log("Session", JSON.stringify(session, null, 2))
} else {
// Not Signed in
res.status(401)
}
res.end()
}
```
### Using getToken()
If you are using JSON Web Tokens you can use the `getToken()` helper to access the contents of the JWT without having to handle JWT decryption / verification yourself. This method can only be used server side.
```js title="pages/api/get-token-example.js"
// This is an example of how to read a JSON Web Token from an API route
import { getToken } from "next-auth/jwt"
export default async (req, res) => {
// If you don't have NEXTAUTH_SECRET set, you will have to pass your secret as `secret` to `getToken`
const token = await getToken({ req })
if (token) {
// Signed in
console.log("JSON Web Token", JSON.stringify(token, null, 2))
} else {
// Not Signed in
res.status(401)
}
res.end()
}
```
<Callout>
You can use the `getToken()` helper function in any application as long as you set the `NEXTAUTH_URL` environment variable and the application is able to read the JWT cookie (e.g. is on the same domain).
</Callout>
<Callout>
Pass `getToken` the same value for `secret` as specified in `pages/api/auth/[...nextauth].js`.
See [the documentation for the JWT option](/reference/configuration/auth-config#jwt) for more information.
</Callout>

View File

@@ -0,0 +1,4 @@
{
"avoid-corporate-link-checking-email-provider": "Email Provider Corporate Proxy Compatibility",
"corporate-proxy": "Corporate Proxies"
}

View File

@@ -0,0 +1,39 @@
---
title: Corporate email sign up
---
If you use Office 365 or Outlook, or potentially other Email systems, you may notice your Email invitation Links not working.
This is because the invitation Email your User is receiving is being scanned by the Email provider. In the specific case of Outlook and their "SafeLink" feature, they send a HEAD request to each link in the Email. This request will trigger the Auth.js catch-all API Route with the users invitation token, in effect using it up.
Therefore, when the user wants to use it themselves, and clicks on the invitation link they will be greeted with an error message that the invitation is invalid.
## Workarounds
### Disable "SafeLink"
The first potential workaround is to simply disable this "SafeLink" feature for your organisation. Microsoft has more details on this [here](https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/safe-links?view=o365-worldwide#do-not-rewrite-the-following-urls-lists-in-safe-links-policies). Obviously this won't be an option for everyone as this is usually a part of corporate IT policy.
### Update Auth.js for 'HEAD' requests
The second option is to modify your `[...nextauth].js` catch-all API route a bit to gracefully handle these initial `HEAD` requests from the email service, without accidentally using up the invitation link.
This can be done by simply returning a `200` response on `HEAD` requests at the very top of the API route, before any other logic is executed.
For example
```jsx title="/pages/api/auth/[...nextauth].js"
import type { NextApiRequest, NextApiResponse } from "next"
import NextAuth from "next-auth"
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
if(req.method === "HEAD") {
return res.status(200)
}
...
}
```
This should allow you to successfully use Auth.js's Email provider behind strict corporate IT settings.

View File

@@ -0,0 +1,91 @@
---
title: Corporate proxy
---
import { Callout } from 'nextra-theme-docs'
Using Auth.js behind a corporate proxy is not supported out of the box. This is due to the fact that the underlying library we use, [`openid-client`](https://npm.im/openid-client) which uses the built-in Node.js `http` / `https` libraries, and those do not support proxys by default:
- [`http` docs](https://nodejs.org/dist/latest-v18.x/docs/api/http.html)
- [`https` docs](https://nodejs.org/dist/latest-v18.x/docs/api/https.html)
Therefore, we'll need to add an additional proxy agent to the http client, such as `https-proxy-agent`.
<Callout type="info">
`openid-client` allows the user to set an `agent` for requests ([source](https://github.com/panva/node-openid-client/blob/main/docs/README.md#customizing-individual-http-requests)).
</Callout>
Thanks to [raphaelpc](https://github.com/raphaelpc) for the below diff, which when applied to `v4.2.1`, adds this agent support to the `client.js` file.
```diff
diff --git a/node_modules/next-auth/core/lib/oauth/client.js b/node_modules/next-auth/core/lib/oauth/client.js
index 77161bd..1082fba 100644
--- a/node_modules/next-auth/core/lib/oauth/client.js
+++ b/node_modules/next-auth/core/lib/oauth/client.js
@@ -7,11 +7,19 @@ exports.openidClient = openidClient;
var _openidClient = require("openid-client");
+var HttpsProxyAgent = require("https-proxy-agent");
+
async function openidClient(options) {
const provider = options.provider;
- if (provider.httpOptions) _openidClient.custom.setHttpOptionsDefaults(provider.httpOptions);
- let issuer;
+ let httpOptions = {};
+ if (provider.httpOptions) httpOptions = { ...provider.httpOptions };
+ if (process.env.http_proxy) {
+ let agent = new HttpsProxyAgent(process.env.http_proxy);
+ httpOptions.agent = agent;
+ }
+ _openidClient.custom.setHttpOptionsDefaults(httpOptions);
+ let issuer;
if (provider.wellKnown) {
issuer = await _openidClient.Issuer.discover(provider.wellKnown);
} else {
```
> For more details, see [this issue](https://github.com/nextauthjs/next-auth/issues/2509#issuecomment-1035410802)
After applying this patch, we can add then add the proxy connecting string via the `http_proxy` environment variable.
### OAuth Provider Issue
If you're having trouble with your [OAuth provider](/reference/providers/oauth-builtin) when using the `https-proxy-agent`, you may be using a provider which requires an extra request to, for example, fetch the users profile picture. In cases like these, you'll have to add the proxy workaround to your provider config as well. Below is an example of how to do that for the **AzureAD** provider, but it should work with any other provider:
```diff
diff --git a/node_modules/next-auth/providers/azure-ad.js b/node_modules/next-auth/providers/azure-ad.js
index 73d96d3..536cd81 100644
--- a/node_modules/next-auth/providers/azure-ad.js
+++ b/node_modules/next-auth/providers/azure-ad.js
@@ -5,6 +5,8 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = AzureAD;
+const HttpsProxyAgent = require('https-proxy-agent');
+
function AzureAD(options) {
var _options$tenantId, _options$profilePhoto;
@@ -22,11 +24,15 @@ function AzureAD(options) {
},
async profile(profile, tokens) {
- const profilePicture = await fetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, {
+ let fetchOptions = {
headers: {
- Authorization: `Bearer ${tokens.access_token}`
- }
- });
+ Authorization: `Bearer ${tokens.access_token}`,
+ },
+ };
+ if (process.env.http_proxy) {
+ fetchOptions.agent = new HttpsProxyAgent(process.env.http_proxy);
+ }
+ const profilePicture = await fetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, fetchOptions);
if (profilePicture.ok) {
const pictureBuffer = await profilePicture.arrayBuffer();
```

View File

@@ -0,0 +1,9 @@
---
title: Overview
sidebar_label: Guides
sidebar_position: 0
---
We're creating internal guides to help understand how to use Auth.js and all the possible configurations and uses cases it supports.
If you can't find what you're looking for, [raise an issue](https://github.com/nextauthjs/next-auth/issues/new/choose) then take a look at our third-party [community resources](/guides/resources).

View File

@@ -0,0 +1,4 @@
{
"ldap-auth": "LDAP Auth",
"usage-with-class-components": "Usage with Class Components"
}

View File

@@ -0,0 +1,79 @@
---
title: LDAP Authentication
---
Auth.js provides the ability to setup a [custom Credential provider](/guides/providers/credentials) which we can take advantage of to authenticate users against an existing LDAP server.
You will need an additional dependency, `ldapjs`, which you can install by running
```bash npm2yarn2pnpm
npm install ldapjs
```
Then you must setup the `CredentialsProvider()` provider key like so:
```js title="[...nextauth].js"
const ldap = require("ldapjs")
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
export default NextAuth({
providers: [
CredentialsProvider({
name: "LDAP",
credentials: {
username: { label: "DN", type: "text", placeholder: "" },
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
// You might want to pull this call out so we're not making a new LDAP client on every login attemp
const client = ldap.createClient({
url: process.env.LDAP_URI,
})
// Essentially promisify the LDAPJS client.bind function
return new Promise((resolve, reject) => {
client.bind(credentials.username, credentials.password, (error) => {
if (error) {
console.error("Failed")
reject()
} else {
console.log("Logged in")
resolve({
username: credentials.username,
password: credentials.password,
})
}
})
})
},
}),
],
callbacks: {
async jwt({ token, user }) {
const isSignIn = user ? true : false
if (isSignIn) {
token.username = user.username
token.password = user.password
}
return token
},
async session({ session, token }) {
return { ...session, user: { username: token.username } }
},
},
})
```
The idea is that once one is authenticated with the LDAP server, one can pass through both the username/DN and password to the JWT stored in the browser.
This is then passed back to any API routes and retrieved as such:
```js title="/pages/api/doLDAPWork.js"
token = await jwt.getToken({
req,
})
const { username, password } = token
```
> Thanks to [Winwardo](https://github.com/Winwardo) for the code example

View File

@@ -0,0 +1,60 @@
---
title: Usage with class components
---
If you want to use the [`useSession()`](/reference/react/#usesession) hook in your class components you can do so with the help of a higher order component or with a render prop.
## Higher Order Component
```js
import { useSession } from "next-auth/react"
const withSession = (Component) => (props) => {
const session = useSession()
// if the component has a render property, we are good
if (Component.prototype.render) {
return <Component session={session} {...props} />
}
// if the passed component is a function component, there is no need for this wrapper
throw new Error(
[
"You passed a function component, `withSession` is not needed.",
"You can `useSession` directly in your component.",
].join("\n")
)
}
// Usage
class ClassComponent extends React.Component {
render() {
const { data: session, status } = this.props.session
return null
}
}
const ClassComponentWithSession = withSession(ClassComponent)
```
## Render Prop
```js
import { useSession } from "next-auth/react"
const UseSession = ({ children }) => {
const session = useSession()
return children(session)
}
// Usage
class ClassComponent extends React.Component {
render() {
return (
<UseSession>
{(session) => <pre>{JSON.stringify(session, null, 2)}</pre>}
</UseSession>
)
}
}
```

View File

@@ -0,0 +1,5 @@
{
"credentials-provider": "Credentials Provider",
"email-provider": "Email Provider",
"custom-provider": "Custom Provider"
}

View File

@@ -0,0 +1,136 @@
---
id: credentials
title: Credentials Provider
---
import { Callout } from 'nextra-theme-docs'
The Credentials provider allows you to handle signing in with arbitrary credentials, such as a username and password, domain, or two factor authentication or hardware device (e.g. YubiKey U2F / FIDO).
It is intended to support use cases where you have an existing system you need to authenticate users against.
It comes with the constraint that users authenticated in this manner are not persisted in the database, and consequently that the Credentials provider can only be used if JSON Web Tokens are enabled for sessions.
<Callout type="warning">
The functionality provided for credentials based authentication is intentionally limited to discourage use of passwords due to the inherent security risks associated with them and the additional complexity associated with supporting usernames and passwords.
</Callout>
## Options
The **Credentials Provider** comes with a set of default options:
- [Credentials Provider options](/reference/providers/credentials)
You can override any of the options to suit your own use case.
## Example - Username / Password
The Credentials provider is specified like other providers, except that you need to define a handler for `authorize()` that accepts credentials submitted via HTTP POST as input and returns either:
1. A `user` object, which indicates the credentials are valid.
If you return an object it will be persisted to the JSON Web Token and the user will be signed in, unless a custom `signIn()` callback is configured that subsequently rejects it.
2. If you return `null` then an error will be displayed advising the user to check their details.
3. If you throw an Error, the user will be sent to the error page with the error message as a query parameter.
The Credentials provider's `authorize()` method also provides the request object as the second parameter (see example below).
```js title="pages/api/auth/[...nextauth].js"
import CredentialsProvider from "next-auth/providers/credentials";
...
providers: [
CredentialsProvider({
// The name to display on the sign in form (e.g. "Sign in with...")
name: "Credentials",
// `credentials` is used to generate a form on the sign in page.
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
// Add logic here to look up the user from the credentials supplied
const user = { id: "1", name: "J Smith", email: "jsmith@example.com" }
if (user) {
// Any object returned will be saved in `user` property of the JWT
return user
} else {
// If you return null then an error will be displayed advising the user to check their details.
return null
// You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
}
}
})
]
...
```
See the [callbacks documentation](/reference/configuration/auth-config#callbacks) for more information on how to interact with the token.
## Example - Web3 / Signin With Ethereum
The credentials provider can also be used to integrate with a service like [Sign-in With Ethereum](https://login.xyz).
For more information, check out the links below:
- [Tutorial](https://docs.login.xyz/integrations/Auth.js)
- [Example App Repo](https://github.com/spruceid/siwe-next-auth-example).
- [Example App Demo](https://siwe-next-auth-example2.vercel.app/).
## Multiple providers
### Example
You can specify more than one credentials provider by specifying a unique `id` for each one.
You can also use them in conjunction with other provider options.
As with all providers, the order you specify them is the order they are displayed on the sign in page.
```js
providers: [
CredentialsProvider({
id: "domain-login",
name: "Domain Account",
async authorize(credentials, req) {
const user = {
/* add function to get user */
}
return user
},
credentials: {
domain: {
label: "Domain",
type: "text ",
placeholder: "CORPNET",
value: "CORPNET",
},
username: { label: "Username", type: "text ", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
}),
CredentialsProvider({
id: "intranet-credentials",
name: "Two Factor Auth",
async authorize(credentials, req) {
const user = {
/* add function to get user */
}
return user
},
credentials: {
email: { label: "Username", type: "text ", placeholder: "jsmith" },
"2fa-key": { label: "2FA Key" },
},
}),
/* ... additional providers ... /*/
]
```
![](/img/signin-complex.png)

View File

@@ -0,0 +1,138 @@
---
title: Using a custom Provider
sidebar_label: Creating a Provider
---
import { Callout } from 'nextra-theme-docs'
You can use an OAuth provider that isn't built-in by using a custom object.
As an example of what this looks like, this is the provider object returned for the Google provider:
```js
{
id: "google",
name: "Google",
type: "oauth",
wellKnown: "https://accounts.google.com/.well-known/openid-configuration",
authorization: { params: { scope: "openid email profile" } },
idToken: true,
checks: ["pkce", "state"],
profile(profile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
}
},
}
```
As you can see, if your provider supports OpenID Connect and the `/.well-known/openid-configuration` endpoint contains support for the `grant_type`: `authorization_code`, you only need to pass the URL to that configuration file and define some basic fields like `name` and `type`.
Otherwise, you can pass a more full set of URLs for each OAuth2.0 flow step, for example:
```js
{
id: "kakao",
name: "Kakao",
type: "oauth",
authorization: "https://kauth.kakao.com/oauth/authorize",
token: "https://kauth.kakao.com/oauth/token",
userinfo: "https://kapi.kakao.com/v2/user/me",
profile(profile) {
return {
id: profile.id,
name: profile.kakao_account?.profile.nickname,
email: profile.kakao_account?.email,
image: profile.kakao_account?.profile.profile_image_url,
}
},
}
```
Replace all the options in this JSON object with the ones from your custom provider - be sure to give it a unique ID and specify the required URLs, and finally add it to the providers array when initializing the library:
```js title="pages/api/auth/[...nextauth].js"
import TwitterProvider from "next-auth/providers/twitter"
...
providers: [
TwitterProvider({
clientId: process.env.TWITTER_ID,
clientSecret: process.env.TWITTER_SECRET,
}),
{
id: 'customProvider',
name: 'CustomProvider',
type: 'oauth',
scope: '' // Make sure to request the users email address
...
}
]
...
```
### Override default options
For built-in providers, in most cases you will only need to specify the `clientId` and `clientSecret`. If you need to override any of the defaults, add your own [options](#options).
Even if you are using a built-in provider, you can override any of these options to tweak the default configuration.
<Callout>
The user provided options are deeply merged with the default options. That means you only have to override part of the options that you need to be different. For example if you want different scopes, overriding `authorization.params.scope` is enough, instead of the whole `authorization` option.
</Callout>
```js title=/api/auth/[...nextauth].js
import Auth0Provider from "next-auth/providers/auth0"
Auth0Provider({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
issuer: process.env.ISSUER,
authorization: { params: { scope: "openid your_custom_scope" } },
})
```
Another example, the `profile` callback will return `id`, `name`, `email` and `picture` by default, but you might need more information from the provider. After setting the correct scopes, you can then do something like this:
```js title=/api/auth/[...nextauth].js
import GoogleProvider from "next-auth/providers/google"
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
profile(profile) {
return {
// Return all the profile information you need.
// The only truly required field is `id`
// to be able identify the account when added to a database
}
},
})
```
An example of how to enable automatic account linking:
```js title=/api/auth/[...nextauth].js
import GoogleProvider from "next-auth/providers/google"
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
allowDangerousEmailAccountLinking: true,
})
```
### Adding a new built-in provider
If you think your custom provider might be useful to others, we encourage you to open a PR and add it to the built-in list so others can discover it much more easily!
You only need to add three changes:
1. Add your config: [`src/providers/{provider}.ts`](https://github.com/nextauthjs/next-auth/tree/main/packages/next-auth/src/providers)<br />
- Make sure you use a named default export, like this: `export default function YourProvider`
- Add two SVG's of the provider logo, like `google-dark.svg` (dark mode) and `google.svg` (light mode), to the `/packages/next-auth/provider-logos/` directory as well as the styling config to the provider config object. See existing provider for example
2. Add provider documentation: [`docs/docs/reference/05-oauth-providers/{provider}.md`](https://github.com/nextauthjs/next-auth/tree/main/docs/docs/reference/05-oauth-providers)
3. Add the new provider name to the `Provider type` dropdown options in [`the provider issue template`](https://github.com/nextauthjs/next-auth/edit/main/.github/ISSUE_TEMPLATE/2_bug_provider.yml)
That's it! 🎉 Others will be able to discover and use this provider much more easily now!

View File

@@ -0,0 +1,218 @@
---
id: email
title: Email Provider
---
import { Callout } from 'nextra-theme-docs'
The Email provider uses email to send "magic links" that can be used to sign in, you will likely have seen these if you have used services like Slack before.
Adding support for signing in via email in addition to one or more OAuth services provides a way for users to sign in if they lose access to their OAuth account (e.g. if it is locked or deleted).
The Email provider can be used in conjunction with (or instead of) one or more OAuth providers.
### How it works
On initial sign in, a **Verification Token** is sent to the email address provided. By default this token is valid for 24 hours. If the Verification Token is used within that time (i.e. by clicking on the link in the email) an account is created for the user and they are signed in.
If someone provides the email address of an _existing account_ when signing in, an email is sent and they are signed into the account associated with that email address when they follow the link in the email.
<Callout>
The Email Provider can be used with both JSON Web Tokens and database sessions, but you **must** configure a database to use it. It is not possible to enable email sign in without using a database.
</Callout>
## Options
The **Email Provider** comes with a set of default options:
- [Email Provider options](/reference/providers/email)
You can override any of the options to suit your own use case.
## Configuration
1. Auth.js does not include `nodemailer` as a dependency, so you'll need to install it yourself if you want to use the Email Provider. Run `npm install nodemailer` or `yarn add nodemailer`.
2. You will need an SMTP account; ideally for one of the [services known to work with `nodemailer`](https://community.nodemailer.com/2-0-0-beta/setup-smtp/well-known-services/).
3. There are two ways to configure the SMTP server connection.
You can either use a connection string or a `nodemailer` configuration object.
2.1 **Using a connection string**
Create an `.env` file to the root of your project and add the connection string and email address.
```js title=".env" {1}
EMAIL_SERVER=smtp://username:password@smtp.example.com:587
EMAIL_FROM=noreply@example.com
```
Now you can add the email provider like this:
```js {3} title="pages/api/auth/[...nextauth].js"
import EmailProvider from "next-auth/providers/email";
...
providers: [
EmailProvider({
server: process.env.EMAIL_SERVER,
from: process.env.EMAIL_FROM
}),
],
```
2.2 **Using a configuration object**
In your `.env` file in the root of your project simply add the configuration object options individually:
```js title=".env"
EMAIL_SERVER_USER=username
EMAIL_SERVER_PASSWORD=password
EMAIL_SERVER_HOST=smtp.example.com
EMAIL_SERVER_PORT=587
EMAIL_FROM=noreply@example.com
```
Now you can add the provider settings to the NextAuth options object in the Email Provider.
```js title="pages/api/auth/[...nextauth].js"
import EmailProvider from "next-auth/providers/email";
...
providers: [
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM
}),
],
```
3. Do not forget to setup one of the database [adapters](/reference/adapters/overview) for storing the Email verification token.
4. You can now sign in with an email address at `/api/auth/signin`.
A user account (i.e. an entry in the Users table) will not be created for the user until the first time they verify their email address. If an email address is already associated with an account, the user will be signed in to that account when they use the link in the email.
## Customizing emails
You can fully customize the sign in email that is sent by passing a custom function as the `sendVerificationRequest` option to `EmailProvider()`.
e.g.
```js {3} title="pages/api/auth/[...nextauth].js"
import EmailProvider from "next-auth/providers/email";
...
providers: [
EmailProvider({
server: process.env.EMAIL_SERVER,
from: process.env.EMAIL_FROM,
sendVerificationRequest({
identifier: email,
url,
provider: { server, from },
}) {
/* your function */
},
}),
]
```
The following code shows the complete source for the built-in `sendVerificationRequest()` method:
```js
import nodemailer from "nodemailer"
async function sendVerificationRequest({
identifier: email,
url,
provider: { server, from },
}) {
const { host } = new URL(url)
const transport = nodemailer.createTransport(server)
await transport.sendMail({
to: email,
from,
subject: `Sign in to ${host}`,
text: text({ url, host }),
html: html({ url, host, email }),
})
}
// Email HTML body
function html({ url, host, email }: Record<"url" | "host" | "email", string>) {
// Insert invisible space into domains and email address to prevent both the
// email address and the domain from being turned into a hyperlink by email
// clients like Outlook and Apple mail, as this is confusing because it seems
// like they are supposed to click on their email address to sign in.
const escapedEmail = `${email.replace(/\./g, "&#8203;.")}`
const escapedHost = `${host.replace(/\./g, "&#8203;.")}`
// Some simple styling options
const backgroundColor = "#f9f9f9"
const textColor = "#444444"
const mainBackgroundColor = "#ffffff"
const buttonBackgroundColor = "#346df1"
const buttonBorderColor = "#346df1"
const buttonTextColor = "#ffffff"
return `
<body style="background: ${backgroundColor};">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="padding: 10px 0px 20px 0px; font-size: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
<strong>${escapedHost}</strong>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="20" cellpadding="0" style="background: ${mainBackgroundColor}; max-width: 600px; margin: auto; border-radius: 10px;">
<tr>
<td align="center" style="padding: 10px 0px 0px 0px; font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
Sign in as <strong>${escapedEmail}</strong>
</td>
</tr>
<tr>
<td align="center" style="padding: 20px 0;">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="border-radius: 5px;" bgcolor="${buttonBackgroundColor}"><a href="${url}" target="_blank" style="font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${buttonTextColor}; text-decoration: none; border-radius: 5px; padding: 10px 20px; border: 1px solid ${buttonBorderColor}; display: inline-block; font-weight: bold;">Sign in</a></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" style="padding: 0px 0px 10px 0px; font-size: 16px; line-height: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
If you did not request this email you can safely ignore it.
</td>
</tr>
</table>
</body>
`
}
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
function text({ url, host }: Record<"url" | "host", string>) {
return `Sign in to ${host}\n${url}\n\n`
}
```
<Callout>
If you want to generate great looking email client compatible HTML with React, check out https://mjml.io
</Callout>
## Customizing the Verification Token
By default, we are generating a random verification token. You can define a `generateVerificationToken` method in your provider options if you want to override it:
```js title="pages/api/auth/[...nextauth].js"
providers: [
EmailProvider({
async generateVerificationToken() {
return "ABC123"
}
})
],
```

View File

@@ -0,0 +1,122 @@
---
title: Community Resources
---
import { Callout } from "nextra-theme-docs"
import Image from "next/image"
<Callout type="info">
These tutorials are contributed by the community. **New submissions and edits
are welcome!**
</Callout>
## Basics
#### [Introduction to Auth.js](https://www.youtube.com/watch?v=npZsJxWntJM) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/youtube.svg" alt="YouTube Logo" />
- This is an introductory video to Auth.js for beginners. In this video, it is explained how to set up authentication in a few easy steps and add different configurations to make it more robust and secure.
#### [Authentication patterns for Next.js](https://nextjs.org/docs/authentication) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Next.js supports multiple patterns for authentication, each designed for different use cases. This guide will allow you to choose your adventure based on your constraints. By Lee Robinson.
#### [Adding Authentication to an existing Next.js Application in no time!](https://dev.to/ndom91/adding-authentication-to-an-existing-serverless-next-js-app-in-no-time-with-nextauth-js-192h) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/devto.svg" alt="Dev.to Logo" />
- This tutorial walks one through adding Auth.js to an existing project. Including setting up the OAuth client id and secret, adding the API routes for authentication, protecting pages and API routes behind that authentication, etc.
#### [Adding social authentication support to a Next.js app](https://getstarted.sh/bulletproof-next/add-social-authentication) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- A tutorial by Arunoda Susirpiala. Checkout [GetStarted](https://getstarted.sh/) for more examples.
#### [How to Authenticate Next.js Apps with Twitter & Auth.js](https://spacejelly.dev/posts/how-to-authenticate-next-js-apps-with-twitter-nextauth-js/) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Learn how to add Twitter authentication and login to a Next.js app both client-side and server-side with Auth.js.
#### [NextJS Authentication Crash Course with Auth.js](https://youtu.be/o_wZIVmWteQ) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/youtube.svg" alt="YouTube Logo" />
- This tutorial dives into the ins and outs of NextAuth, including using the Email, Github, Twitter and Auth0 providers in under an hour.
#### [Create your own Auth.js Login Pages](https://youtu.be/kB6YNYZ63fw) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/youtube.svg" alt="YouTube Logo" />
- This tutorial shows you how to jump in and create your own custom login pages versus using the ones provided by Auth.js
#### [Passwordless Authentication with next-auth](https://www.youtube.com/watch?v=GPBD3acOx_M) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/youtube.svg" alt="YouTube Logo" />
- A video tutorial by Xiaoru Li from Prisma.
#### [How to authenticate Next.js Apps with Sign-In With Ethereum (SIWE) & Auth.js](https://docs.login.xyz/integrations/Auth.js) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Learn how to use Sign-In With Ethereum to authenticate your users with their existing Ethereum wallets - identifiers they personally control.
- Example application: [`spruceid/siwe-next-auth-example`](https://github.com/spruceid/siwe-next-auth-example)
#### [Next.js Authentication with Okta and Auth.js 4.0](https://thetombomb.com/posts/nextjs-nextauth-okta) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Learn how to perform authentication with an OIDC Application in Okta and Auth.js.
## Fullstack
#### [Build a FullStack App with Next.js, Auth.js, Supabase & Prisma](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-242389284337222224) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
In this [free course](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-242389284337222224), you'll learn how to build a full-stack app using the following technologies:
- **Next.js** - The React framework for building the UI of the app and the REST API
- **Auth.js** - For implementing passwordless and OAuth authentication
- **Supabase** - For persisting the app data into a PostgreSQL database and storing media files
- **Prisma** - For making it easy to read and write data from our app from and to the database
The app that we'll work on in this course is called **_SupaVacation_**. It is an online marketplace for vacation rentals where users can browse through all the properties for rent, bookmark their favorite ones, and even rent their own properties.
> Here's [a live demo](https://supa-vacation.vercel.app/) of the app's final version. It is what your app should look likes after completing this course. Feel free to play with it to get an overview of all the features you'll be working on.
#### [Magic Link Authentication in Next.js with NextAuth and Fauna](https://alterclass.io/tutorials/magic-link-authentication-in-nextjs-with-nextauth-and-fauna) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
Learn how to implement passwordless/magic link authentication with database storage in your Next.js projects using NextAuth and Fauna DB.
> The final version of the project's code can be found on [Github](https://github.com/AlterClassIO/magic-next-auth). You can use it as a starting point for any Next.js app that requires passwordless authentication.
This tutorial covers:
- Configuring Next.js, Auth.js, and Fauna to work together seamlessly
- Using Next.js dynamic API routes to handle authentication requests
- Using Fauna and the Fauna Adapter for `next-auth` to persist users, email sign in tokens, and sessions
- Creating custom login and confirmation pages with React + Tailwind CSS
- Customizing the sign-in email and sending a welcome email to new users
> You can also preview the example live [here](https://magic-next-auth.vercel.app/).
#### [Passwordless Authentication with Next.js, Prisma, and next-auth](https://dev.to/prisma/passwordless-authentication-with-next-js-prisma-and-next-auth-5g8g) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/devto.svg" alt="Dev.to Logo" />
- In this post, you'll learn how to add passwordless authentication to your Next.js app using Prisma and next-auth. By the end of this tutorial, your users will be able to log in to your app with either their GitHub account or a Slack-styled magic link sent right to their Email inbox. By Xiaoru Li.
#### [Fullstack Authentication Example with Next.js and Auth.js](https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-nextjs-api-routes-auth) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- This example shows how to implement a full-stack app in TypeScript with Next.js using Prisma Client as a backend. It also demonstrates how to implement authentication using Auth.js. By Nikolas Burk at Prisma.
## Advanced
#### [Add auth support to a Next.js app with a custom backend](https://arunoda.me/blog/add-auth-support-to-a-next-js-app-with-a-custom-backend) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- A tutorial by Arunoda Susirpiala.
#### [How to Configure Azure AD B2C Authentication with Next.js](https://benjaminwfox.com/blog/tech/how-to-configure-azure-b2c-with-nextjs) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Configuring authentication with Azure B2C in Next.js is not a particularly straight forward process. We'll look at how to facilitate this using the Auth.js library. By Ben Fox.
#### [Sign in with Apple in NextJS](https://thesiddd.com/blog/apple-auth) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- This tutorial walks step by step on how to get sign in with Apple working (both locally and on a deployed website) using Auth.js.
#### [Using Auth.js with Magic links](https://dev.to/narciero/using-nextauth-js-with-magic-links-df4) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/devto.svg" alt="Dev.to Logo" />
- Learn how to use [Magic.Link](https://magic.link) authentication with [Auth.js](https://authjs.dev) to enable passwordless authentication without a database.
## Database
#### [Create a Auth.js Custom Adapter with HarperDB & Next.js](https://spacejelly.dev/posts/how-to-create-a-nextauth-js-custom-adapter-with-harperdb-next-js/) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- Use a custom database in a Custom Adapter for persisted Auth.js sessions using HarperDB as an example.
- Video tutorial also available: [https://www.youtube.com/watch?v=pu7xBv7sZ8s](https://www.youtube.com/watch?v=pu7xBv7sZ8s)
#### [Using Auth.js with Prisma and PlanetScale serverless databases](https://github.com/planetscale/nextjs-planetscale-starter) <Image style={{ marginLeft: '0.5rem', display: 'inline' }} width={24} height={24} src="/img/external.svg" alt="External" />
- How to set up a PlanetScale database to fetch and store user / account data with the Prisma adapter.

View File

@@ -0,0 +1,3 @@
{
"testing-with-cypress": "Testing with Cypress"
}

View File

@@ -0,0 +1,129 @@
---
title: Testing with Cypress
---
import { Callout } from 'nextra-theme-docs'
To test an implementation of Auth.js, we encourage you to use [Cypress](https://cypress.io).
## Setting up Cypress
To get started, install the dependencies:
```bash npm2yarn2pnpm
npm install --save-dev cypress cypress-social-logins @testing-library/cypress
```
<Callout>
If you are using username/password based login, you will not need the `cypress-social-login` dependency.
</Callout>
Cypress will install and initialize the folder structure with example integration tests, a folder for plugins, etc.
Next you will have to create some configuration files for Cypress.
First, the primary cypress config:
```js title="cypress.json"
{
"baseUrl": "http://localhost:3000",
"chromeWebSecurity": false
}
```
This initial Cypress config will tell Cypress where to find your site on initial launch as well as allow it to open up URLs at domains that aren't your page, for example to be able to login to a social provider.
Second, a cypress file for environment variables. These can be defined in `cypress.json` under the key `env` as well, however since we're storing username / passwords in here we should keep those in a separate file and only commit `cypress.json` to version control, not `cypress.env.json`.
```js title="cypress.env.json"
{
"GOOGLE_USER": "username@company.com",
"GOOGLE_PW": "password",
"COOKIE_NAME": "next-auth.session-token",
"SITE_NAME": "http://localhost:3000"
}
```
You must change the login credentials you want to use, but you can also redefine the name of the `GOOGLE_*` variables if you're using a different provider. `COOKIE_NAME`, however, must be set to that value for Auth.js.
Third, if you're using the `cypress-social-login` plugin, you must add this to your `/cypress/plugins/index.js` file like so:
```js title="cypress/plugins/index.js"
const { GoogleSocialLogin } = require("cypress-social-logins").plugins
module.exports = (on, config) => {
on("task", {
GoogleSocialLogin: GoogleSocialLogin,
})
}
```
Finally, you can also add the following npm scripts to your `package.json`:
```json
"test:e2e:open": "cypress open",
"test:e2e:run": "cypress run"
```
## Writing a test
Once we've got all that configuration out of the way, we can begin writing tests to login using Auth.js.
The basic login test looks like this:
```js title="cypress/integration/login.js"
describe("Login page", () => {
before(() => {
cy.log(`Visiting https://company.tld`)
cy.visit("/")
})
it("Login with Google", () => {
const username = Cypress.env("GOOGLE_USER")
const password = Cypress.env("GOOGLE_PW")
const loginUrl = Cypress.env("SITE_NAME")
const cookieName = Cypress.env("COOKIE_NAME")
const socialLoginOptions = {
username,
password,
loginUrl,
headless: true,
logs: false,
isPopup: true,
loginSelector: `a[href="${Cypress.env(
"SITE_NAME"
)}/api/auth/signin/google"]`,
postLoginSelector: ".unread-count",
}
return cy
.task("GoogleSocialLogin", socialLoginOptions)
.then(({ cookies }) => {
cy.clearCookies()
const cookie = cookies
.filter((cookie) => cookie.name === cookieName)
.pop()
if (cookie) {
cy.setCookie(cookie.name, cookie.value, {
domain: cookie.domain,
expiry: cookie.expires,
httpOnly: cookie.httpOnly,
path: cookie.path,
secure: cookie.secure,
})
Cypress.Cookies.defaults({
preserve: cookieName,
})
// remove the two lines below if you need to stay logged in
// for your remaining tests
cy.visit("/api/auth/signout")
cy.get("form").submit()
}
})
})
})
```
Things to note here include, that you must adjust the CSS selector defined under `postLoginSelector` to match a selector found on your page after the user is logged in. This is how Cypress knows whether it succeeded or not. Also, if you're using another provider, you will have to adjust the `loginSelector` URL.

View File

@@ -0,0 +1,67 @@
import { readdir } from "fs/promises"
import Image from "next/image"
import Marquee from "../components/marquee.jsx"
import Triangle from "../components/triangle.jsx"
export default function Index({ files }) {
return (
<div className="flex flex-col justify-center">
<div className="flex justify-center items-center flex-col md:flex-row gap-2">
<Triangle className="h-48" />
<div className="flex flex-col gap-2">
<h1 className="text-7xl font-bold text-center md:text-left">
Auth.js
</h1>
<p className="text-2xl text-center md:text-left">
Authentication for the Web.
</p>
</div>
<div className="btns"></div>
</div>
{/* <svg
className="absolute top-0 left-0 -z-10 w-[50vw] lg:w-[40vw]"
width="1056" height="855" viewBox="0 0 1056 855" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M888.078 42.3027C465.467 1294.94 73.851 662.761 -266.667 854.807L-294.519 -12.0732C-119.086 -25.2807 234.783 -53.0438 246.789 -58.4364C261.797 -65.1771 1132.31 -620.045 1050.51 -275.273C1001.28 -160.866 980.447 -231.483 888.078 42.3027Z" fill="url(#paint0_radial_228_76)"/>
<defs>
<radialGradient id="paint0_radial_228_76" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(666.999 571.116) rotate(-129.513) scale(513.947 862.777)">
<stop stopColor="#FF4400"/>
<stop offset="1" stopColor="#111"/>
</radialGradient>
</defs>
</svg>
<svg
className="absolute -top-10 -right-36 -z-10 w-[65vw] lg:w-[45vw]"
width="1405" height="1025" viewBox="0 0 1405 1025" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1180.05 977.4C483.802 708.04 103.247 143.506 0 -105.091L1102.61 -196C1418.53 307.367 1876.29 1246.76 1180.05 977.4Z" fill="url(#paint0_radial_228_83)"/>
<defs>
<radialGradient id="paint0_radial_228_83" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(498 619) rotate(-46.5881) scale(548.572 1194.34)">
<stop stopColor="#BB44CC"/>
<stop offset="1" stopColor="#111"/>
</radialGradient>
</defs>
</svg>
<svg
className="absolute bottom-32 lg:bottom-10 right-20 -z-10 w-[80vw] lg:w-full"
width="2402" height="275" viewBox="0 0 2402 275" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M305.668 155.376C1150.52 -387.169 3270.85 708.01 2011.14 262.274L1847.48 804.627C1613.84 721.267 1142.31 553.804 1125.29 550.832C1104 547.117 -168.361 431.431 18.8067 264.119C109.949 220.108 121.011 273.958 305.668 155.376Z" fill="url(#paint0_radial_228_78)"/>
<defs>
<radialGradient id="paint0_radial_228_78" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(883.5 -66) rotate(93.0267) scale(757.557 879.417)">
<stop stopColor="#44BBCC"/>
<stop offset="1" stopColor="#111"/>
</radialGradient>
</defs>
</svg> */}
<Marquee className="absolute top-0 left-0 w-full h-full" files={files} />
</div>
)
}
export async function getStaticProps() {
const dir = process.cwd()
const files = await readdir(`${dir}/public/img/providers/`)
return { props: { files: files.filter((e) => e.includes("dark")) } }
}

View File

@@ -0,0 +1,250 @@
---
id: dgraph
title: Dgraph
---
import { Callout } from "nextra-theme-docs"
This is the Dgraph Adapter for [`next-auth`](https://authjs.dev).
## Getting Started
1. Install the necessary packages
```bash npm2yarn
npm install next-auth @next-auth/dgraph-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 { DgraphAdapter } from "@next-auth/dgraph-adapter"
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/provideres/oauth-builtin
providers: [],
adapter: DgraphAdapter({
endpoint: process.env.DGRAPH_GRAPHQL_ENDPOINT,
authToken: process.env.DGRAPH_GRAPHQL_KEY,
// you can omit the following properties if you are running an unsecure schema
authHeader: process.env.AUTH_HEADER, // default: "Authorization",
jwtSecret: process.env.SECRET,
}),
})
```
## Quick start with the unsecure schema
The quickest way to use Dgraph is by applying the unsecure schema to your [local](https://dgraph.io/docs/graphql/admin/#modifying-a-schema) Dgraph instance or if using Dgraph [cloud](https://dgraph.io/docs/cloud/cloud-quick-start/#the-schema) you can paste the schema in the codebox to update.
<Callout type="warning">
This approach is not secure or for production use, and does not require a `jwtSecret`.
</Callout>
> This schema is adapted for use in Dgraph and based upon our main [schema](/reference/adapters/models)
#### Unsecure schema
```graphql
type Account {
id: ID
type: String
provider: String @search(by: [hash])
providerAccountId: String @search(by: [hash])
refreshToken: String
expires_at: Int64
accessToken: String
token_type: String
refresh_token: String
access_token: String
scope: String
id_token: String
session_state: String
user: User @hasInverse(field: "accounts")
}
type Session {
id: ID
expires: DateTime
sessionToken: String @search(by: [hash])
user: User @hasInverse(field: "sessions")
}
type User {
id: ID
name: String
email: String @search(by: [hash])
emailVerified: DateTime
image: String
accounts: [Account] @hasInverse(field: "user")
sessions: [Session] @hasInverse(field: "user")
}
type VerificationToken {
id: ID
identifier: String @search(by: [hash])
token: String @search(by: [hash])
expires: DateTime
}
```
## Securing your database
For production deployments you will want to restrict the access to the types used
by next-auth. The main form of access control used in Dgraph is via `@auth` directive alongide types in the schema.
#### Secure schema
```graphql
type Account
@auth(
delete: { rule: "{$nextAuth: { eq: true } }" }
add: { rule: "{$nextAuth: { eq: true } }" }
query: { rule: "{$nextAuth: { eq: true } }" }
update: { rule: "{$nextAuth: { eq: true } }" }
) {
id: ID
type: String
provider: String @search(by: [hash])
providerAccountId: String @search(by: [hash])
refreshToken: String
expires_at: Int64
accessToken: String
token_type: String
refresh_token: String
access_token: String
scope: String
id_token: String
session_state: String
user: User @hasInverse(field: "accounts")
}
type Session
@auth(
delete: { rule: "{$nextAuth: { eq: true } }" }
add: { rule: "{$nextAuth: { eq: true } }" }
query: { rule: "{$nextAuth: { eq: true } }" }
update: { rule: "{$nextAuth: { eq: true } }" }
) {
id: ID
expires: DateTime
sessionToken: String @search(by: [hash])
user: User @hasInverse(field: "sessions")
}
type User
@auth(
query: {
or: [
{
rule: """
query ($userId: String!) {queryUser(filter: { id: { eq: $userId } } ) {id}}
"""
}
{ rule: "{$nextAuth: { eq: true } }" }
]
}
delete: { rule: "{$nextAuth: { eq: true } }" }
add: { rule: "{$nextAuth: { eq: true } }" }
update: {
or: [
{
rule: """
query ($userId: String!) {queryUser(filter: { id: { eq: $userId } } ) {id}}
"""
}
{ rule: "{$nextAuth: { eq: true } }" }
]
}
) {
id: ID
name: String
email: String @search(by: [hash])
emailVerified: DateTime
image: String
accounts: [Account] @hasInverse(field: "user")
sessions: [Session] @hasInverse(field: "user")
}
type VerificationToken
@auth(
delete: { rule: "{$nextAuth: { eq: true } }" }
add: { rule: "{$nextAuth: { eq: true } }" }
query: { rule: "{$nextAuth: { eq: true } }" }
update: { rule: "{$nextAuth: { eq: true } }" }
) {
id: ID
identifier: String @search(by: [hash])
token: String @search(by: [hash])
expires: DateTime
}
# Dgraph.Authorization {"VerificationKey":"<YOUR JWT SECRET HERE>","Header":"<YOUR AUTH HEADER HERE>","Namespace":"<YOUR CUSTOM NAMESPACE HERE>","Algo":"HS256"}
```
#### Dgraph.Authorization
In order to secure your graphql backend define the `Dgraph.Authorization` object at the
bottom of your schema and provide `authHeader` and `jwtSecret` values to the DgraphClient.
```js
# Dgraph.Authorization {"VerificationKey":"<YOUR JWT SECRET HERE>","Header":"<YOUR AUTH HEADER HERE>","Namespace":"YOUR CUSTOM NAMESPACE HERE","Algo":"HS256"}
```
#### VerificationKey and jwtSecret
This is the key used to sign the JWT. Ex. `process.env.SECRET` or `process.env.APP_SECRET`.
#### Header and authHeader
The `Header` tells Dgraph where to lookup a JWT within the headers of the incoming requests made to the dgraph server.
You have to configure it at the bottom of your schema file. This header is the same as the `authHeader` property you
provide when you instantiate the `DgraphClient`.
#### The nextAuth secret
The `$nextAuth` secret is securely generated using the `jwtSecret` and injected by the DgraphAdapter in order to allow interacting with the JWT DgraphClient for anonymous user requests made within the system `ie. login, register`. This allows
secure interactions to be made with all the auth types required by next-auth. You have to specify it for each auth rule of
each type defined in your secure schema.
```js
type VerificationRequest
@auth(
delete: { rule: "{$nextAuth: { eq: true } }" },
add: { rule: "{$nextAuth: { eq: true } }" },
query: { rule: "{$nextAuth: { eq: true } }" },
update: { rule: "{$nextAuth: { eq: true } }" }
) {
...
}
```
## Working with JWT session and @auth directive
Dgraph only works with HS256 or RS256 algorithms. If you want to use session jwt to securely interact with your dgraph
database you must customize next-auth `encode` and `decode` functions, as the default algorithm is HS512. You can
further customize the jwt with roles if you want to implement [`RBAC logic`](https://dgraph.io/docs/graphql/authorization/directive/#role-based-access-control).
```js
import * as jwt from "jsonwebtoken"
export default NextAuth({
session: {
strategy: "jwt",
},
jwt: {
secret: process.env.SECRET,
encode: async ({ secret, token }) => {
return jwt.sign({ ...token, userId: token.id }, secret, {
algorithm: "HS256",
expiresIn: 30 * 24 * 60 * 60, // 30 days
})
},
decode: async ({ secret, token }) => {
return jwt.verify(token, secret, { algorithms: ["HS256"] })
},
},
})
```
Once your `Dgraph.Authorization` is defined in your schema and the JWT settings are set, this will allow you to define
[`@auth rules`](https://dgraph.io/docs/graphql/authorization/authorization-overview/) for every part of your schema.

View File

@@ -0,0 +1,145 @@
---
id: dynamodb
title: 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.
By default, the adapter expects a table with a partition key `pk` and a sort key `sk`, as well as a global secondary index named `GSI1` with `GSI1PK` as partition key and `GSI1SK` as sorting key. To automatically delete sessions and verification requests after they expire using [dynamodb TTL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) you should [enable the TTL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html) with attribute name 'expires'. 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`, `@next-auth/dynamodb-adapter`, `@aws-sdk/client-dynamodb` and `@aws-sdk/lib-dynamodb`
```bash npm2yarn2pnpm
npm install next-auth @next-auth/dynamodb-adapter @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
```
2. Add this adapter to your `pages/api/auth/[...nextauth].js` next-auth configuration object.
You need to pass `DynamoDBDocument` client from the modular [`aws-sdk`](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-dynamodb-utilities.html) v3 to the adapter.
The default table name is `next-auth`, but you can customise that by passing `{ tableName: 'your-table-name' }` as the second parameter in the adapter.
```javascript title="pages/api/auth/[...nextauth].js"
import { DynamoDB, DynamoDBClientConfig } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import { DynamoDBAdapter } from "@next-auth/dynamodb-adapter"
const config: DynamoDBClientConfig = {
credentials: {
accessKeyId: process.env.NEXT_AUTH_AWS_ACCESS_KEY as string,
secretAccessKey: process.env.NEXT_AUTH_AWS_SECRET_KEY as string,
},
region: process.env.NEXT_AUTH_AWS_REGION,
};
const client = DynamoDBDocument.from(new DynamoDB(config), {
marshallOptions: {
convertEmptyValues: true,
removeUndefinedValues: true,
convertClassInstanceToMap: true,
},
})
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(
client
),
...
});
```
(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. retrieving all sessions for a user).
- Only one table needs to be replicated if you want to go multi-region.
> This schema is adapted for use in DynamoDB and based upon our main [schema](/reference/adapters/models)
![DynamoDB Table](https://i.imgur.com/hGZtWDq.png)
You can create this table with infrastructure as code using [`aws-cdk`](https://github.com/aws/aws-cdk) with the following table definition:
```javascript title=stack.ts
new dynamodb.Table(this, `NextAuthTable`, {
tableName: "next-auth",
partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
sortKey: { name: "sk", type: dynamodb.AttributeType.STRING },
timeToLiveAttribute: "expires",
}).addGlobalSecondaryIndex({
indexName: "GSI1",
partitionKey: { name: "GSI1PK", type: dynamodb.AttributeType.STRING },
sortKey: { name: "GSI1SK", type: dynamodb.AttributeType.STRING },
})
```
Alternatively, you can use this cloudformation template:
```yaml title=cloudformation.yaml
NextAuthTable:
Type: "AWS::DynamoDB::Table"
Properties:
TableName: next-auth
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
- AttributeName: GSI1PK
AttributeType: S
- AttributeName: GSI1SK
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
GlobalSecondaryIndexes:
- IndexName: GSI1
Projection:
ProjectionType: ALL
KeySchema:
- AttributeName: GSI1PK
KeyType: HASH
- AttributeName: GSI1SK
KeyType: RANGE
TimeToLiveSpecification:
AttributeName: expires
Enabled: true
```
## Custom Schema
You can configure your custom table schema by passing the `options` key to the adapter constructor:
```
const adapter = DynamoDBAdapter(client, {
tableName: "custom-table-name",
partitionKey: "custom-pk",
sortKey: "custom-sk",
indexName: "custom-index-name",
indexPartitionKey: "custom-index-pk",
indexSortKey: "custom-index-sk",
})
```

View File

@@ -0,0 +1,83 @@
---
id: fauna
title: FaunaDB
---
This is the Fauna Adapter for [`next-auth`](https://authjs.dev). 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 [authjs.dev/reference/adapters/fauna](https://authjs.dev/reference/adapters/fauna).
## Getting Started
1. Install the necessary packages
```bash npm2yarn
npm install next-auth @next-auth/fauna-adapter faunadb
```
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 { Client as FaunaClient } from "faunadb"
import { FaunaAdapter } from "@next-auth/fauna-adapter"
const client = new FaunaClient({
secret: "secret",
scheme: "http",
domain: "localhost",
port: 8443,
})
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/
providers: [],
adapter: FaunaAdapter(client)
...
})
```
## Schema
Run the following commands inside of the `Shell` tab in the Fauna dashboard to setup the appropriate collections and indexes.
```javascript
CreateCollection({ name: "accounts" })
CreateCollection({ name: "sessions" })
CreateCollection({ name: "users" })
CreateCollection({ name: "verification_tokens" })
```
```javascript
CreateIndex({
name: "account_by_provider_and_provider_account_id",
source: Collection("accounts"),
unique: true,
terms: [
{ field: ["data", "provider"] },
{ field: ["data", "providerAccountId"] },
],
})
CreateIndex({
name: "session_by_session_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_token_by_identifier_and_token",
source: Collection("verification_tokens"),
unique: true,
terms: [{ field: ["data", "identifier"] }, { field: ["data", "token"] }],
})
```
> This schema is adapted for use in Fauna and based upon our main [schema](/reference/adapters/models)

View File

@@ -0,0 +1,78 @@
---
id: firebase
title: Firebase
---
import { Callout } from "nextra-theme-docs"
<Callout type="warning">
This adapter is still experimental and does not work with Auth.js 4 or newer. If you would like to help out upgrading it, please visit [this PR](https://github.com/nextauthjs/next-auth/pull/3873)
</Callout>
This is the Firebase Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
## Getting Started
1. Install the necessary packages
```bash npm2yarn
npm install next-auth @next-auth/firebase-adapter@experimental
```
2. Add this adapter to your `pages/api/auth/[...nextauth].js` next-auth configuration object.
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { FirebaseAdapter } from "@next-auth/firebase-adapter"
import firebase from "firebase/app"
import "firebase/firestore"
const firestore = (
firebase.apps[0] ?? firebase.initializeApp(/* your config */)
).firestore()
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
adapter: FirebaseAdapter(firestore),
...
})
```
## Options
When initializing the firestore adapter, you must pass in the firebase config object with the details from your project. More details on how to obtain that config object can be found [here](https://support.google.com/firebase/answer/7015592).
An example firebase config looks like this:
```js
const firebaseConfig = {
apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
authDomain: "myapp-project-123.firebaseapp.com",
databaseURL: "https://myapp-project-123.firebaseio.com",
projectId: "myapp-project-123",
storageBucket: "myapp-project-123.appspot.com",
messagingSenderId: "65211879809",
appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
measurementId: "G-8GSGZQ44ST",
}
```
See [firebase.google.com/docs/web/setup](https://firebase.google.com/docs/web/setup) for more details.
<Callout>
**From Firebase**
**Caution**: We do not recommend manually modifying an app's Firebase config file or object. If you initialize an app with invalid or missing values for any of these required "Firebase options", then your end users may experience serious issues.
For open source projects, we generally do not recommend including the app's Firebase config file or object in source control because, in most cases, your users should create their own Firebase projects and point their apps to their own Firebase resources (via their own Firebase config file or object).
</Callout>

View File

@@ -0,0 +1,113 @@
---
id: mikro-orm
title: MikroORM
---
To use this Adapter, you need to install Mikro ORM, the driver that suits your database, and the separate `@next-auth/mikro-orm-adapter` package:
```bash npm2yarn
npm install next-auth @next-auth/mikro-orm-adapter @mikro-orm/core @mikro-orm/[YOUR DRIVER]
```
Configure Auth.js to use the MikroORM Adapter:
```typescript title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import { MikroOrmAdapter } from "@next-auth/mikro-orm-adapter"
export default NextAuth({
adapter: MikroOrmAdapter({
// MikroORM options object. Ref: https://mikro-orm.io/docs/next/configuration#driver
dbName: "./db.sqlite",
type: "sqlite",
debug: process.env.DEBUG === "true" || process.env.DEBUG?.includes("db"),
}),
providers: [],
})
```
## Setup
### Passing custom entities
The MikroORM adapter ships with its own set of entities. If you'd like to extend them, you can optionally pass them to the adapter.
> This schema is adapted for use in MikroORM and based upon our main [schema](/reference/adapters/models)
```typescript title="pages/api/auth/[...nextauth].ts"
import config from "config/mikro-orm.ts"
import {
Cascade,
Collection,
Entity,
OneToMany,
PrimaryKey,
Property,
Unique,
} from "@mikro-orm/core"
import { defaultEntities } from "@next-auth/mikro-orm-adapter"
const { Account, Session } = defaultEntities
@Entity()
export class User implements defaultEntities.User {
@PrimaryKey()
id: string = randomUUID()
@Property({ nullable: true })
name?: string
@Property({ nullable: true })
@Unique()
email?: string
@Property({ type: "Date", nullable: true })
emailVerified: Date | null = null
@Property({ nullable: true })
image?: string
@OneToMany({
entity: () => Session,
mappedBy: (session) => session.user,
hidden: true,
orphanRemoval: true,
cascade: [Cascade.ALL],
})
sessions = new Collection<Session>(this)
@OneToMany({
entity: () => Account,
mappedBy: (account) => account.user,
hidden: true,
orphanRemoval: true,
cascade: [Cascade.ALL],
})
accounts = new Collection<Account>(this)
@Enum({ hidden: true })
role = "ADMIN"
}
export default NextAuth({
adapter: MikroOrmAdapter(config, { entities: { User } }),
})
```
### Including the default entities in your MikroORM config
You may want to include the defaultEntities in your MikroORM configuration to include them in Migrations etc.
To achieve that include them in your "entities" array:
```typescript title="config/mikro-orm.ts"
import { Options } from "@mikro-orm/core";
import { defaultEntities } from "@next-auth/mikro-orm-adapter"
const config: Options = {
...
entities: [VeryImportantEntity, ...Object.values(defaultEntities)],
};
export default config;
```

View File

@@ -0,0 +1,120 @@
---
id: models
title: Models
---
import { Callout } from "nextra-theme-docs"
Auth.js can be used with any database. Models tell you what structures Auth.js expects from your database. Models will vary slightly depending on which adapter you use, but in general, will look something like this. Each adapter's model/schema will be slightly adapted for its needs, but will look very much like this schema below:
```mermaid
erDiagram
User ||--|{ Account : ""
User {
string id
string name
string email
timestamp emailVerified
string image
}
User ||--|{ Session : ""
Session {
string id
timestamp expires
string sessionToken
string userId
}
Account {
string id
string userId
string type
string provider
string providerAccountId
string refresh_token
string access_token
int expires_at
string token_type
string scope
string id_token
string session_state
string oauth_token_secret
string oauth_token
}
VerificationToken {
string identifier
string token
timestamp expires
}
```
More information about each Model / Table can be found below.
<Callout>
You can [create your own adapter](/guides/adapters/creating-a-database-adapter) if you want to use Auth.js with a database that is not supported out of the box, or you have to change fields on any of the models.
</Callout>
---
## User
The User model is for information such as the user's name and email address.
Email address is optional, but if one is specified for a User then it must be unique.
<Callout>
If a user first signs in with OAuth then their email address is automatically populated using the one from their OAuth profile, if the OAuth provider returns one.
This provides a way to contact users and for users to maintain access to their account and sign in using email in the event they are unable to sign in with the OAuth provider in future (if the [Email Provider](/getting-started/email-tutorial) is configured).
</Callout>
User creation in the database is automatic, and happens when the user is logging in for the first time with a provider. The default data saved is `id`, `name`, `email` and `image`. You can add more profile data by returning extra fields in your [OAuth provider's `profile()`](/reference/providers/oauth) callback.
## Account
The Account model is for information about OAuth accounts associated with a User. It will usually contain `access_token`, `id_token` and other OAuth specific data. [`TokenSet`](https://github.com/panva/node-openid-client/blob/main/docs/README.md#new-tokensetinput) from `openid-client` might give you an idea of all the fields.
<Callout>
In case of an OAuth 1.0 provider (like Twitter), you will have to look for `oauth_token` and `oauth_token_secret` string fields. GitHub also has an extra `refresh_token_expires_in` integer field. You have to make sure that your database schema includes these fields.
</Callout>
A single User can have multiple Accounts, but each Account can only have one User.
Linking Accounts to Users happen automatically, only when they have the same e-mail address, and the user is currently signed in. Check the [FAQ](/concepts/faq#security) for more information why this is a requirement.
<Callout>
You can manually unlink accounts, if your adapter implements the `unlinkAccount` method. Make sure to take all the necessary security steps to avoid data loss.
</Callout>
<Callout>
Linking and unlinking accounts through an API is a planned feature: https://github.com/nextauthjs/next-auth/issues/230
</Callout>
## Session
The Session model is used for database sessions. It is not used if JSON Web Tokens are enabled. Keep in mind, that you can use a database to persist Users and Accounts, and still use JWT for sessions. See the [`session.strategy`](/reference/configuration/auth-config) option.
A single User can have multiple Sessions, each Session can only have one User.
<Callout>
When a Session is read, we check if it's `expires` field indicates an invalid session, and delete it from the database. You can also do this clean-up periodically in the background to avoid our extra delete call to the database during an active session retrieval. This might result in a slight performance increase in a few cases.
</Callout>
## Verification Token
The Verification Token model is used to store tokens for passwordless sign in.
A single User can have multiple open Verification Tokens (e.g. to sign in to different devices).
It has been designed to be extendable for other verification purposes in the future (e.g. 2FA / short codes).
<Callout>
Auth.js makes sure that every token is usable only once, and by default has a short (1 day, can be configured by [`maxAge`](/reference/providers/email)) lifetime. If your user did not manage to finish the sign-in flow in time, they will have to start the sign-in process again.
</Callout>
<Callout>
Due to users forgetting or failing at the sign-in flow, you might end up with unwanted rows in your database, that you might have to periodically clean up to avoid filling the database up with unnecessary data.
</Callout>
## RDBMS Naming Convention
In the Auth.js v4 some schemas for the providers which support classic RDBMS type databases, like Prisma and TypeORM, have ended up with column names with mixed casing, i.e. snake_case and camelCase. If this is an issue for you or your underlying database system, please take a look at the "Naming Convention" section in the Prisma or TypeORM page.

View File

@@ -0,0 +1,64 @@
---
id: mongodb
title: MongoDB
---
The MongoDB adapter does not handle connections automatically, so you will have to make sure that you pass the Adapter a `MongoClient` that is connected already. Below you can see an example how to do this.
## Usage
1. Install the necessary packages
```bash npm2yarn2pnpm
npm install next-auth @next-auth/mongodb-adapter mongodb
```
2. Add `lib/mongodb.ts`
```ts
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb"
if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise: Promise<MongoClient>
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
```
3. Add this adapter to your `pages/api/auth/[...nextauth].js` next-auth configuration object.
```js
import NextAuth from "next-auth"
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "../../../lib/mongodb"
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/providers/oauth
export default NextAuth({
adapter: MongoDBAdapter(clientPromise),
...
})
```

View File

@@ -0,0 +1,115 @@
---
id: neo4j
title: Neo4j
---
This is the Neo4j Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
## Getting Started
1. Install the necessary packages
```bash npm2yarn
npm install next-auth @next-auth/neo4j-adapter neo4j-driver
```
2. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
```javascript title="pages/api/auth/[...nextauth].js"
import neo4j from "neo4j-driver"
import { Neo4jAdapter } from "@next-auth/neo4j-adapter"
const driver = neo4j.driver(
"bolt://localhost",
neo4j.auth.basic("neo4j", "password")
)
const neo4jSession = driver.session()
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: Neo4jAdapter(neo4jSession),
...
})
```
## Schema
### Node labels
The following node labels are used.
- User
- Account
- Session
- VerificationToken
### Relationships
The following relationships and relationship labels are used.
- (:User)-[:HAS_ACCOUNT]->(:Account)
- (:User)-[:HAS_SESSION]->(:Session)
### Properties
This schema is adapted for use in Neo4J and is based upon our main [models](/reference/adapters/models). Please check there for the node properties. Relationships have no properties.
### Indexes
Optimum indexes will vary on your edition of Neo4j i.e. community or enterprise, and in case you have your own additional data on the nodes. Below are basic suggested indexes.
1. For **both** Community Edition & Enterprise Edition create constraints and indexes
```cypher
CREATE CONSTRAINT user_id_constraint IF NOT EXISTS
ON (u:User) ASSERT u.id IS UNIQUE;
CREATE INDEX user_id_index IF NOT EXISTS
FOR (u:User) ON (u.id);
CREATE INDEX user_email_index IF NOT EXISTS
FOR (u:User) ON (u.email);
CREATE CONSTRAINT session_session_token_constraint IF NOT EXISTS
ON (s:Session) ASSERT s.sessionToken IS UNIQUE;
CREATE INDEX session_session_token_index IF NOT EXISTS
FOR (s:Session) ON (s.sessionToken);
```
2.a. For Community Edition **only** create single-property indexes
```cypher
CREATE INDEX account_provider_index IF NOT EXISTS
FOR (a:Account) ON (a.provider);
CREATE INDEX account_provider_account_id_index IF NOT EXISTS
FOR (a:Account) ON (a.providerAccountId);
CREATE INDEX verification_token_identifier_index IF NOT EXISTS
FOR (v:VerificationToken) ON (v.identifier);
CREATE INDEX verification_token_token_index IF NOT EXISTS
FOR (v:VerificationToken) ON (v.token);
```
2.b. For Enterprise Edition **only** create composite node key constraints and indexes
```cypher
CREATE CONSTRAINT account_provider_composite_constraint IF NOT EXISTS
ON (a:Account) ASSERT (a.provider, a.providerAccountId) IS NODE KEY;
CREATE INDEX account_provider_composite_index IF NOT EXISTS
FOR (a:Account) ON (a.provider, a.providerAccountId);
CREATE CONSTRAINT verification_token_composite_constraint IF NOT EXISTS
ON (v:VerificationToken) ASSERT (v.identifier, v.token) IS NODE KEY;
CREATE INDEX verification_token_composite_index IF NOT EXISTS
FOR (v:VerificationToken) ON (v.identifier, v.token);
```

View File

@@ -0,0 +1,10 @@
---
title: Database Adapters
---
import { Callout } from "nextra-theme-docs"
<Callout type="warning">
`@auth/*-adapter` is work in progress. for the time being, please go to
[NextAuth.js Adapters](https://next-auth.js.org/adapters/overview).
</Callout>

View File

@@ -0,0 +1,65 @@
---
id: pouchdb
title: PouchDB
---
import { Callout } from "nextra-theme-docs"
<Callout type="warning">
This adapter is still experimental and does not work with Auth.js 4 or newer. If you would like to help out upgrading it, please [open a PR](https://github.com/nextauthjs/next-auth/tree/main/packages)
</Callout>
This is the PouchDB Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
Depending on your architecture you can use PouchDB's http adapter to reach any database compliant with the CouchDB protocol (CouchDB, Cloudant, ...) or use any other PouchDB compatible adapter (leveldb, in-memory, ...)
## Getting Started
> **Prerequisites**: Your PouchDB instance MUST provide the `pouchdb-find` plugin since it is used internally by the adapter to build and manage indexes
1. Install `next-auth` and `@next-auth/pouchdb-adapter`
```bash npm2yarn
npm install next-auth @next-auth/pouchdb-adapter
```
2. Add this adapter to your `pages/api/auth/[...nextauth].js` next-auth configuration object
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { PouchDBAdapter } from "@next-auth/pouchdb-adapter"
import PouchDB from "pouchdb"
// Setup your PouchDB instance and database
PouchDB.plugin(require("pouchdb-adapter-leveldb")) // Any other adapter
.plugin(require("pouchdb-find")) // Don't forget the `pouchdb-find` plugin
const pouchdb = new PouchDB("auth_db", { adapter: "leveldb" })
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
adapter: PouchDBAdapter(pouchdb),
// ...
})
```
## Advanced
### Memory-First Caching Strategy
If you need to boost your authentication layer performance, you may use PouchDB's powerful sync features and various adapters, to build a memory-first caching strategy.
Use an in-memory PouchDB as your main authentication database, and synchronize it with any other persisted PouchDB. You may do a one way, one-off replication at startup from the persisted PouchDB into the in-memory PouchDB, then two-way, continuous sync.
This will most likely not increase performance much in a serverless environment due to various reasons such as concurrency, function startup time increases, etc.
For more details, please see https://pouchdb.com/api.html#sync

View File

@@ -0,0 +1,211 @@
---
id: prisma
title: Prisma
---
import { Callout } from 'nextra-theme-docs'
To use this Adapter, you need to install Prisma Client, Prisma CLI, and the separate `@next-auth/prisma-adapter` package:
```bash npm2yarn
npm install next-auth @prisma/client @next-auth/prisma-adapter
npm install prisma --save-dev
```
Configure your Auth.js to use the Prisma Adapter:
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
})
```
Schema for the Prisma Adapter (`@next-auth/prisma-adapter`)
## Setup
### Create the Prisma schema
You need to use at least Prisma 2.26.0. Create a schema file in `prisma/schema.prisma` similar to this one:
> This schema is adapted for use in Prisma and based upon our main [schema](/reference/adapters/models)
```json title="schema.prisma"
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
shadowDatabaseUrl = env("SHADOW_DATABASE_URL") // Only needed when using a cloud provider that doesn't support the creation of new databases, like Heroku. Learn more: https://pris.ly/migrate-shadow
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["referentialActions"] // You won't need this in Prisma 3.X or higher.
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
```
<Callout>
When using the MySQL connector for Prisma, the [Prisma `String` type](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string) gets mapped to `varchar(191)` which may not be long enough to store fields such as `id_token` in the `Account` model. This can be avoided by explicitly using the `Text` type with `@db.Text`.
</Callout>
### Create the database schema with Prisma Migrate
```
npx prisma migrate dev
```
This will create an SQL migration file and execute it.
Note that you will need to specify your database 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.
To learn more about [Prisma Migrate](https://www.prisma.io/migrate), check out the [Migrate docs](https://www.prisma.io/docs/concepts/components/prisma-migrate).
### Generate Client
Once you have saved your schema, use the Prisma CLI to generate the Prisma Client:
```
npx prisma generate
```
To configure your database to use the new schema (i.e. create tables and columns) use the `prisma migrate` command:
```
npx prisma migrate dev
```
### MongoDB
Prisma supports MongoDB, and so does Auth.js. Following the instructions of the [Prisma documentation](https://www.prisma.io/docs/concepts/database-connectors/mongodb) on the MongoDB connector, things you have to change are:
1. Make sure that the id fields are mapped correctly
```prisma
id String @id @default(auto()) @map("_id") @db.ObjectId
```
2. The Native database type attribute to `@db.String` from `@db.Text`.
```prisma
refresh_token String? @db.String
access_token String? @db.String
id_token String? @db.String
```
Everything else should be the same.
## Naming Conventions
If mixed snake_case and camelCase column names is an issue for you and/or your underlying database system, we recommend using Prisma's `@map()`([see the documentation here](https://www.prisma.io/docs/concepts/components/prisma-schema/names-in-underlying-database)) feature to change the field names. This won't affect Auth.js, but will allow you to customize the column names to whichever naming convention you wish.
For example, moving to `snake_case` and plural table names.
```json title="schema.prisma"
model Account {
id String @id @default(cuid())
userId String @map("user_id")
type String
provider String
providerAccountId String @map("provider_account_id")
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
@@map("accounts")
}
model Session {
id String @id @default(cuid())
sessionToken String @unique @map("session_token")
userId String @map("user_id")
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("sessions")
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime? @map("email_verified")
image String?
accounts Account[]
sessions Session[]
@@map("users")
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
@@map("verificationtokens")
}
```

View File

@@ -0,0 +1,88 @@
---
id: sequelize
title: Sequelize
---
import { Callout } from "nextra-theme-docs"
This is the Sequelize Adapter for [`next-auth`](https://authjs.dev).
## Getting Started
1. Install the necessary packages
```bash npm2yarn
npm install next-auth @next-auth/sequelize-adapter sequelize
```
<Callout type="warning">
You'll also have to manually install [the driver for your database](https://sequelize.org/master/manual/getting-started.html) of choice.
</Callout>
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 SequelizeAdapter from "@next-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](https://authjs.dev/reference/adapters/models) in your database via [migrations](https://sequelize.org/master/manual/migrations.html). In development, you are able to call [`sequelize.sync()`](https://sequelize.org/master/manual/model-basics.html#model-synchronization) 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](/reference/adapters/models)
```js
import NextAuth from "next-auth"
import SequelizeAdapter from "@next-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
...
})
```
## Using custom models
Sequelize models are option to customization like so:
```js
import NextAuth from "next-auth"
import SequelizeAdapter, { models } from "@next-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,
}),
},
}),
})
```

View File

@@ -0,0 +1,311 @@
---
id: supabase
title: Supabase
---
import { Callout } from "nextra-theme-docs"
# Supabase
This is the Supabase Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
<Callout>
This adapter is developed by the community and not officially maintained or supported by Supabase. It uses the Supabase Database to store user and session data in a separate `next_auth` schema. It is a standalone Auth server that does not interface with Supabase Auth and therefore provides a different feature set.
If youre looking for an officially maintained Auth server with additional features like [built-in email server](https://supabase.com/docs/guides/auth/auth-email#configure-email-settings?utm_source=authjs-docs&medium=referral&campaign=authjs), [phone auth](https://supabase.com/docs/guides/auth/auth-twilio?utm_source=authjs-docs&medium=referral&campaign=authjs), and [Multi Factor Authentication (MFA / 2FA)](https://supabase.com/contact/mfa?utm_source=authjs-docs&medium=referral&campaign=authjs), please use [Supabase Auth](https://supabase.com/auth) with the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs?utm_source=authjs-docs&medium=referral&campaign=authjs).
</Callout>
## Getting Started
1. Install `@supabase/supabase-js`, `next-auth` and `@next-auth/supabase-adapter`.
```bash npm2yarn2pnpm
npm install @supabase/supabase-js next-auth @next-auth/supabase-adapter
```
2. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
```js title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import { SupabaseAdapter } from "@next-auth/supabase-adapter"
// 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/oauth-builtin
providers: [...],
adapter: SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY,
}),
// ...
})
```
## Setup
### Create the `next_auth` schema in Supabase
Setup your database as described in our main [schema](/reference/adapters/models), by copying the SQL schema below in the Supabase [SQL Editor](https://app.supabase.com/project/_/sql).
Alternatively you can select the NextAuth Quickstart card on the [SQL Editor page](https://app.supabase.com/project/_/sql), or [create a migration with the Supabase CLI](https://supabase.com/docs/guides/cli/local-development#database-migrations?utm_source=authjs-docs&medium=referral&campaign=authjs).
```sql
--
-- Name: next_auth; Type: SCHEMA;
--
CREATE SCHEMA next_auth;
GRANT USAGE ON SCHEMA next_auth TO service_role;
GRANT ALL ON SCHEMA next_auth TO postgres;
--
-- Create users table
--
CREATE TABLE IF NOT EXISTS next_auth.users
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
name text,
email text,
"emailVerified" timestamp with time zone,
image text,
CONSTRAINT users_pkey PRIMARY KEY (id),
CONSTRAINT email_unique UNIQUE (email)
);
GRANT ALL ON TABLE next_auth.users TO postgres;
GRANT ALL ON TABLE next_auth.users TO service_role;
--- uid() function to be used in RLS policies
CREATE FUNCTION next_auth.uid() RETURNS uuid
LANGUAGE sql STABLE
AS $$
select
coalesce(
nullif(current_setting('request.jwt.claim.sub', true), ''),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
)::uuid
$$;
--
-- Create sessions table
--
CREATE TABLE IF NOT EXISTS next_auth.sessions
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
expires timestamp with time zone NOT NULL,
"sessionToken" text NOT NULL,
"userId" uuid,
CONSTRAINT sessions_pkey PRIMARY KEY (id),
CONSTRAINT sessionToken_unique UNIQUE ("sessionToken"),
CONSTRAINT "sessions_userId_fkey" FOREIGN KEY ("userId")
REFERENCES next_auth.users (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
);
GRANT ALL ON TABLE next_auth.sessions TO postgres;
GRANT ALL ON TABLE next_auth.sessions TO service_role;
--
-- Create accounts table
--
CREATE TABLE IF NOT EXISTS next_auth.accounts
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
type text NOT NULL,
provider text NOT NULL,
"providerAccountId" text NOT NULL,
refresh_token text,
access_token text,
expires_at bigint,
token_type text,
scope text,
id_token text,
session_state text,
oauth_token_secret text,
oauth_token text,
"userId" uuid,
CONSTRAINT accounts_pkey PRIMARY KEY (id),
CONSTRAINT provider_unique UNIQUE (provider, "providerAccountId"),
CONSTRAINT "accounts_userId_fkey" FOREIGN KEY ("userId")
REFERENCES next_auth.users (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
);
GRANT ALL ON TABLE next_auth.accounts TO postgres;
GRANT ALL ON TABLE next_auth.accounts TO service_role;
--
-- Create verification_tokens table
--
CREATE TABLE IF NOT EXISTS next_auth.verification_tokens
(
identifier text,
token text,
expires timestamp with time zone NOT NULL,
CONSTRAINT verification_tokens_pkey PRIMARY KEY (token),
CONSTRAINT token_unique UNIQUE (token),
CONSTRAINT token_identifier_unique UNIQUE (token, identifier)
);
GRANT ALL ON TABLE next_auth.verification_tokens TO postgres;
GRANT ALL ON TABLE next_auth.verification_tokens TO service_role;
```
### Expose the `next_auth` schema in Supabase
Expose the `next_auth` schema via the Serverless API in the [API settings](https://app.supabase.com/project/_/settings/api) by adding `next_auth` to the "Exposed schemas" list.
When developing locally add `next_auth` to the `schemas` array in the `config.toml` file in the `supabase` folder that was generated by the [Supabase CLI](https://supabase.com/docs/guides/cli/local-development#initialize-your-project?utm_source=authjs-docs&medium=referral&campaign=authjs).
## Enabling Row Level Security (RLS)
Postgres provides a powerful feature called [Row Level Security (RLS)](https://supabase.com/docs/guides/auth/row-level-security?utm_source=authjs-docs&medium=referral&campaign=authjs) to limit access to data.
This works by sending a signed JWT to your [Supabase Serverless API](https://supabase.com/docs/guides/api?utm_source=authjs-docs&medium=referral&campaign=authjs). There is two steps to make this work with NextAuth:
### 1. Generate the Supabase `access_token` JWT in the session callback
To sign the JWT use the `jsonwebtoken` package:
```bash npm2yarn2pnpm
npm install jsonwebtoken
```
Using the [NexthAuth Session callback](/reference/configuration/auth-config#callbacks) create the Supabase `access_token` and append it to the `session` object.
To sign the JWT use the Supabase JWT secret which can be found in the [API settings](https://app.supabase.com/project/_/settings/api)
```js title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import { SupabaseAdapter } from "@next-auth/supabase-adapter"
import jwt from "jsonwebtoken"
// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/oauth-builtin
providers: [...],
adapter: SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY,
}),
callbacks: {
async session({ session, user }) {
const signingSecret = process.env.SUPABASE_JWT_SECRET
if (signingSecret) {
const payload = {
aud: "authenticated",
exp: Math.floor(new Date(session.expires).getTime() / 1000),
sub: user.id,
email: user.email,
role: "authenticated",
}
session.supabaseAccessToken = jwt.sign(payload, signingSecret)
}
return session
},
},
// ...
})
```
### 2. Inject the Supabase `access_token` JWT into the Supabase Client
For example, given the following public schema:
```sql
/**
* USERS
* Note: This table contains user data. Users should only be able to view and update their own data.
*/
create table users (
-- UUID from next_auth.users
id uuid not null primary key,
name text,
email text,
image text,
constraint "users_id_fkey" foreign key ("id")
references next_auth.users (id) match simple
on update no action
on delete cascade -- if user is deleted in NextAuth they will also be deleted in our public table.
);
alter table users enable row level security;
create policy "Can view own user data." on users for select using (next_auth.uid() = id);
create policy "Can update own user data." on users for update using (next_auth.uid() = id);
/**
* This trigger automatically creates a user entry when a new user signs up via NextAuth.
*/
create function public.handle_new_user()
returns trigger as $$
begin
insert into public.users (id, name, email, image)
values (new.id, new.name, new.email, new.image);
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on next_auth.users
for each row execute procedure public.handle_new_user();
```
The `supabaseAccessToken` is now available on the `session` object and can be passed to the supabase-js client. This works in any environment: client-side, server-side (API routes, SSR), as well as in middleware edge functions!
```js
// ...
// Use `useSession()` or `unstable_getServerSession()` to get the NextAuth session.
const { supabaseAccessToken } = session
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
{
global: {
headers: {
Authorization: `Bearer ${supabaseAccessToken}`,
},
},
}
)
// Now you can query with RLS enabled.
const { data, error } = await supabase.from("users").select("*")
```
## Usage with TypeScript
You can pass types that were generated with the Supabase CLI to the Supabase Client to get enhanced type safety and auto completion.
Creating a new supabase client object:
```tsx
import { createClient } from "@supabase/supabase-js"
import { Database } from "../database.types"
const supabase = createClient<Database>()
```
### Extend the session type with the `supabaseAccessToken`
In order to extend the `session` object with the `supabaseAccessToken` we need to extend the `session` interface in a `types/next-auth.d.ts` file:
```ts title="types/next-auth.d.ts"
import NextAuth, { DefaultSession } from "next-auth"
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
// A JWT which can be used as Authorization header with supabase-js for RLS.
supabaseAccessToken?: string
user: {
/** The user's postal address. */
address: string
} & DefaultSession["user"]
}
}
```

View File

@@ -0,0 +1,237 @@
---
id: typeorm
title: TypeORM
---
import { Callout } from 'nextra-theme-docs'
This Adapter is used to support SQL-flavored databases (like SQLite, MySQL, MSSQL, MariaDB, CockroachDB, etc.) through [TypeORM](https://typeorm.io), and mostly kept around for legacy reasons. (See the warning below.)
<Callout>
If you previously used this Adapter with MongoDB, check out the [MongoDB Adapter](/reference/adapters/mongodb) instead.
</Callout>
<Callout type="warning">
In the future, we might split up this adapter to support single flavors of SQL for easier maintenance and reduced bundle size.
</Callout>
## Usage
To use this Adapter, you need to install the following packages:
```bash npm2yarn
npm install next-auth @next-auth/typeorm-legacy-adapter typeorm
```
Configure your Auth.js to use the TypeORM Adapter:
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter"
export default NextAuth({
adapter: TypeORMLegacyAdapter("yourconnectionstring"),
...
})
```
`TypeORMLegacyAdapter` takes either a connection string, or a [`ConnectionOptions`](https://github.com/typeorm/typeorm/blob/master/docs/connection-options.md) object as its first parameter.
## Custom models
The TypeORM adapter uses [`Entity` classes](https://github.com/typeorm/typeorm/blob/master/docs/entities.md) to define the shape of your data.
If you want to override the default entities (for example to add a `role` field to your `UserEntity`), you will have to do the following:
> This schema is adapted for use in TypeORM and based upon our main [schema](/reference/adapters/models)
1. Create a file containing your modified entities:
(The file below is based on the [default entities](https://github.com/nextauthjs/next-auth/blob/main/packages/adapter-typeorm-legacy/src/entities.ts))
```diff title="lib/entities.ts"
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
OneToMany,
ValueTransformer,
} from "typeorm"
const transformer: Record<"date" | "bigint", ValueTransformer> = {
date: {
from: (date: string | null) => date && new Date(parseInt(date, 10)),
to: (date?: Date) => date?.valueOf().toString(),
},
bigint: {
from: (bigInt: string | null) => bigInt && parseInt(bigInt, 10),
to: (bigInt?: number) => bigInt?.toString(),
},
}
@Entity({ name: "users" })
export class UserEntity {
@PrimaryGeneratedColumn("uuid")
id!: string
@Column({ type: "varchar", nullable: true })
name!: string | null
@Column({ type: "varchar", nullable: true, unique: true })
email!: string | null
@Column({ type: "varchar", nullable: true, transformer: transformer.date })
emailVerified!: string | null
@Column({ type: "varchar", nullable: true })
image!: string | null
+ @Column({ type: "varchar", nullable: true })
+ role!: string | null
@OneToMany(() => SessionEntity, (session) => session.userId)
sessions!: SessionEntity[]
@OneToMany(() => AccountEntity, (account) => account.userId)
accounts!: AccountEntity[]
}
@Entity({ name: "accounts" })
export class AccountEntity {
@PrimaryGeneratedColumn("uuid")
id!: string
@Column({ type: "uuid" })
userId!: string
@Column()
type!: string
@Column()
provider!: string
@Column()
providerAccountId!: string
@Column({ type: "varchar", nullable: true })
refresh_token!: string | null
@Column({ type: "varchar", nullable: true })
access_token!: string | null
@Column({
nullable: true,
type: "bigint",
transformer: transformer.bigint,
})
expires_at!: number | null
@Column({ type: "varchar", nullable: true })
token_type!: string | null
@Column({ type: "varchar", nullable: true })
scope!: string | null
@Column({ type: "varchar", nullable: true })
id_token!: string | null
@Column({ type: "varchar", nullable: true })
session_state!: string | null
@Column({ type: "varchar", nullable: true })
oauth_token_secret!: string | null
@Column({ type: "varchar", nullable: true })
oauth_token!: string | null
@ManyToOne(() => UserEntity, (user) => user.accounts, {
createForeignKeyConstraints: true,
})
user!: UserEntity
}
@Entity({ name: "sessions" })
export class SessionEntity {
@PrimaryGeneratedColumn("uuid")
id!: string
@Column({ unique: true })
sessionToken!: string
@Column({ type: "uuid" })
userId!: string
@Column({ transformer: transformer.date })
expires!: string
@ManyToOne(() => UserEntity, (user) => user.sessions)
user!: UserEntity
}
@Entity({ name: "verification_tokens" })
export class VerificationTokenEntity {
@PrimaryGeneratedColumn("uuid")
id!: string
@Column()
token!: string
@Column()
identifier!: string
@Column({ transformer: transformer.date })
expires!: string
}
```
2. Pass them to `TypeORMLegacyAdapter`
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter"
import * as entities from "lib/entities"
export default NextAuth({
adapter: TypeORMLegacyAdapter("yourconnectionstring", { entities }),
...
})
```
<Callout>
The `synchronize: true` option in TypeORM will generate SQL that exactly matches the entities. This will automatically apply any changes it finds in the entity model. This is a useful option in development.
</Callout>
<Callout type="warning">
Using synchronize in production
`synchronize: true` should not be enabled against production databases as it may cause data loss if the configured schema does not match the expected schema! We recommend that you synchronize/migrate your production database at build-time.
</Callout>
## Naming Conventions
If mixed snake_case and camelCase column names are an issue for you and/or your underlying database system, we recommend using TypeORM's naming strategy feature to change the target field names. There is a package called `typeorm-naming-strategies` which includes a `snake_case` strategy which will translate the fields from how Auth.js expects them, to snake_case in the actual database.
For example, you can add the naming convention option to the connection object in your NextAuth config.
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter"
import { SnakeNamingStrategy } from 'typeorm-naming-strategies'
import { ConnectionOptions } from "typeorm"
const connection: ConnectionOptions = {
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
namingStrategy: new SnakeNamingStrategy()
}
export default NextAuth({
adapter: TypeORMLegacyAdapter(connection),
...
})
```

View File

@@ -0,0 +1,67 @@
---
id: upstash-redis
title: Upstash Redis
---
To use this Adapter, you need to install `@upstash/redis` and `@next-auth/upstash-redis-adapter` package:
```bash npm2yarn
npm install @upstash/redis @next-auth/upstash-redis-adapter
```
Configure your Auth.js to use the Upstash Redis Adapter:
```javascript title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { UpstashRedisAdapter } from "@next-auth/upstash-redis-adapter"
import upstashRedisClient from "@upstash/redis"
const redis = upstashRedisClient(
process.env.UPSTASH_REDIS_URL,
process.env.UPSTASH_REDIS_TOKEN
)
export default NextAuth({
adapter: UpstashRedisAdapter(redis),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
})
```
## Using Multiple Apps with a Single Upstash Redis Instance
The Upstash free-tier allows for only one Redis instance. If you have multiple Next-Auth connected apps using this instance, you need different key prefixes for every app.
You can change the prefixes by passing an `options` object as the second argument to the adapter factory function.
The default values for this object are:
```js
const defaultOptions = {
baseKeyPrefix: "",
accountKeyPrefix: "user:account:",
accountByUserIdPrefix: "user:account:by-user-id:",
emailKeyPrefix: "user:email:",
sessionKeyPrefix: "user:session:",
sessionByUserIdKeyPrefix: "user:session:by-user-id:",
userKeyPrefix: "user:",
verificationTokenKeyPrefix: "user:token:",
}
```
Usually changing the `baseKeyPrefix` should be enough for this scenario, but for more custom setups, you can also change the prefixes of every single key.
Example:
```js
export default NextAuth({
...
adapter: UpstashRedisAdapter(redis, {baseKeyPrefix: "app2:"})
...
})
```

View File

@@ -0,0 +1,240 @@
---
id: xata
title: Xata
---
This adapter allows using next-auth with Xata as a database to store users, sessions, and more. The preferred way to create a Xata project and use Xata databases is using the [Xata Command Line Interface (CLI)](https://docs.xata.io/cli/getting-started). The CLI allows generating a `XataClient` that will help you work with Xata in a safe way, and that this adapter depends on.
<!-- @todo add GIFs -->
## Getting Started
Let's first make sure we have everything installed and configured. We're going to need:
- next-auth + adapter
- the Xata CLI
- to configure the CLI
We can do this like so:
```bash npm2yarn2pnpm
# Install next-auth + adapter
npm install next-auth @next-auth/xata-adapter
# Install the Xata CLI globally if you don't already have it
npm install --location=global @xata.io/cli
# Login
xata auth login
```
Now that we're ready, let's create a new Xata project using our next-auth schema that the Xata adapter can work with. To do that, copy and paste this schema file into your project's directory:
```json title="schema.json"
{
"formatVersion": "",
"tables": [
{
"name": "nextauth_users",
"columns": [
{
"name": "email",
"type": "email"
},
{
"name": "emailVerified",
"type": "datetime"
},
{
"name": "name",
"type": "string"
},
{
"name": "image",
"type": "string"
}
]
},
{
"name": "nextauth_accounts",
"columns": [
{
"name": "user",
"type": "link",
"link": {
"table": "nextauth_users"
}
},
{
"name": "type",
"type": "string"
},
{
"name": "provider",
"type": "string"
},
{
"name": "providerAccountId",
"type": "string"
},
{
"name": "refresh_token",
"type": "string"
},
{
"name": "access_token",
"type": "string"
},
{
"name": "expires_at",
"type": "int"
},
{
"name": "token_type",
"type": "string"
},
{
"name": "scope",
"type": "string"
},
{
"name": "id_token",
"type": "text"
},
{
"name": "session_state",
"type": "string"
}
]
},
{
"name": "nextauth_verificationTokens",
"columns": [
{
"name": "identifier",
"type": "string"
},
{
"name": "token",
"type": "string"
},
{
"name": "expires",
"type": "datetime"
}
]
},
{
"name": "nextauth_users_accounts",
"columns": [
{
"name": "user",
"type": "link",
"link": {
"table": "nextauth_users"
}
},
{
"name": "account",
"type": "link",
"link": {
"table": "nextauth_accounts"
}
}
]
},
{
"name": "nextauth_users_sessions",
"columns": [
{
"name": "user",
"type": "link",
"link": {
"table": "nextauth_users"
}
},
{
"name": "session",
"type": "link",
"link": {
"table": "nextauth_sessions"
}
}
]
},
{
"name": "nextauth_sessions",
"columns": [
{
"name": "sessionToken",
"type": "string"
},
{
"name": "expires",
"type": "datetime"
},
{
"name": "user",
"type": "link",
"link": {
"table": "nextauth_users"
}
}
]
}
]
}
```
Now, run the following command:
```bash
xata init --schema=./path/to/your/schema.json
```
The CLI will walk you through a setup process where you choose a [workspace](https://docs.xata.io/concepts/workspaces) (kind of like a GitHub org or a Vercel team) and an appropriate database. We recommend using a fresh database for this, as we'll augment it with tables that next-auth needs.
Once you're done, you can continue using next-auth in your project as expected, like creating a `./pages/api/auth/[...nextauth]` route.
```typescript title="pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
const client = new XataClient()
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
})
```
Now to Xata-fy this route, let's add the Xata client and adapter:
```diff
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
+import { XataAdapter } from "@next-auth/xata-adapter"
+import { XataClient } from "../../../xata" // or wherever you've chosen to create the client
+const client = new XataClient()
export default NextAuth({
+ adapter: XataAdapter(client),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
})
```
This fully sets up your next-auth site to work with Xata.
## Contributing
This is an open-source project created by humans, and as such, might have a few issues. If you experience any of these, we recommend [opening issues](https://github.com/nextauthjs/next-auth/issues/new?assignees=&labels=triage&template=1_bug_framework.yml&title=Issue%20on%20Xata%20adapter&description=I%20experienced%20this%20issue:\n##%20Reproduction%20Steps:\n\n-) that can help us solve problems and build reliable software.

View File

@@ -0,0 +1,461 @@
---
title: Initialization
---
import { Callout } from "nextra-theme-docs"
## Options
Options are passed to Auth.js when initializing it in a server environment like a Next.js API Route.
### providers
- **Default value**: `[]`
- **Required**: _Yes_
#### Description
An array of authentication providers for signing in (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. This can be one of the built-in providers or an object with a custom provider.
Refer to the list of [all available Oauth providers](/reference/providers/oauth-builtin) and the [Oauth tutorial](/getting-started/oauth-tutorial) on how to use them.
---
### secret
- **Default value**: `string` (_SHA hash of the "options" object_) in development, no default in production.
- **Required**: _Yes, in production!_
#### Description
A random string is used to hash tokens, sign/encrypt cookies and generate cryptographic keys.
If you set [`NEXTAUTH_SECRET`](#nextauth_secret) as an environment variable, you don't have to define this option.
If no value specified specified in development (and there is no `NEXTAUTH_SECRET` variable either), it uses a hash for all configuration options, including OAuth Client ID / Secrets for entropy.
<Callout type="warning">
Not providing any `secret` or `NEXTAUTH_SECRET` will throw [an
error](/reference/errors#no_secret) in production.
</Callout>
You can quickly create a good value on the command line via this `openssl` command.
```bash
$ openssl rand -base64 32
```
<Callout>
If you rely on the default secret generation in development, you might notice
JWT decryption errors, since the secret changes whenever you change your
configuration. Defining an explicit secret will make this problem go away. We
will likely make this option mandatory, even in development, in the future.
</Callout>
---
### session
- **Default value**: `object`
- **Required**: _No_
#### Description
The `session` object and all properties on it are optional.
Default values for this option are shown below:
```js
session: {
// Choose how you want to save the user session.
// The default is `"jwt"`, an encrypted JWT (JWE) stored in the session cookie.
// If you use an `adapter` however, we default it to `"database"` instead.
// You can still force a JWT session by explicitly defining `"jwt"`.
// When using `"database"`, the session cookie will only contain a `sessionToken` value,
// which is used to look up the session in the database.
strategy: "database",
// Seconds - How long until an idle session expires and is no longer valid.
maxAge: 30 * 24 * 60 * 60, // 30 days
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
updateAge: 24 * 60 * 60, // 24 hours
}
```
---
### jwt
- **Default value**: `object`
- **Required**: _No_
#### Description
JSON Web Tokens can be used for session tokens if enabled with `session: { strategy: "jwt" }` option. JSON Web Tokens are enabled by default if you have not specified an adapter. JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour. See the [Override JWT `encode` and `decode` methods](#override-jwt-encode-and-decode-methods) advanced option.
#### JSON Web Token Options
```js
jwt: {
// The maximum age of the Auth.js issued JWT in seconds.
// Defaults to `session.maxAge`.
maxAge: 60 * 60 * 24 * 30,
// You can define your own encode/decode functions for signing and encryption
async encode() {},
async decode() {},
}
```
An example JSON Web Token contains a payload like this:
```js
{
name: 'Iain Collins',
email: 'me@iaincollins.com',
picture: 'https://example.com/image.jpg',
iat: 1594601838,
exp: 1597193838
}
```
#### JWT Helper
You can use the built-in `getToken()` helper method to verify and decrypt the token, like this:
```js
import { getToken } from "next-auth/jwt"
const secret = process.env.NEXTAUTH_SECRET
export default async function handler(req, res) {
// if using `NEXTAUTH_SECRET` env variable, we detect it, and you won't actually need to `secret`
// const token = await getToken({ req })
const token = await getToken({ req, secret })
console.log("JSON Web Token", token)
res.end()
}
```
_For convenience, this helper function is also able to read and decode tokens passed from the `Authorization: 'Bearer token'` HTTP header._
**Required**
The getToken() helper requires the following options:
- `req` - (object) Request object
- `secret` - (string) JWT Secret. Use `NEXTAUTH_SECRET` instead.
You must also pass _any options configured on the `jwt` option_ to the helper.
e.g. Including custom session `maxAge` and custom signing and/or encryption keys or options
**Optional**
It also supports the following options:
- `secureCookie` - (boolean) Use secure prefixed cookie name
By default, the helper function will attempt to determine if it should use the secure prefixed cookie (e.g. `true` in production and `false` in development, unless NEXTAUTH_URL contains an HTTPS URL).
- `cookieName` - (string) Session token cookie name
The `secureCookie` option is ignored if `cookieName` is explicitly specified.
- `raw` - (boolean) Get raw token (not decoded)
If set to `true` returns the raw token without decrypting or verifying it.
<Callout>
The JWT is stored in the Session Token cookie, the same cookie used for tokens
with database sessions.
</Callout>
---
### pages
- **Default value**: `{}`
- **Required**: _No_
#### Description
Specify URLs to be used if you want to create custom sign in, sign out and error pages.
Pages specified will override the corresponding built-in page.
_For example:_
```js
pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error', // Error code passed in query string as ?error=
verifyRequest: '/auth/verify-request', // (used for check email message)
newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest)
}
```
<Callout>
When using this configuration, ensure that these pages actually exist. For
example `error: '/auth/error'` refers to a page file at `pages/auth/error.js`.
</Callout>
See the documentation for the [creating custom pages guide](/guides/basics/pages) for more information.
---
### callbacks
- **Default value**: `object`
- **Required**: _No_
#### Description
Callbacks are asynchronous functions you can use to control what happens when an action is performed.
Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.
You can specify a handler for any of the callbacks below.
```js
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
return true
},
async redirect({ url, baseUrl }) {
return baseUrl
},
async session({ session, token, user }) {
return session
},
async jwt({ token, user, account, profile, isNewUser }) {
return token
}
}
```
See [our callbacks guide](/guides/basics/callbacks) for more information on how to use the callback functions.
---
### events
- **Default value**: `object`
- **Required**: _No_
#### Description
Events are asynchronous functions that do not return a response, they are useful for audit logging.
You can specify a handler for any of these events below - e.g. for debugging or to create an audit log.
The content of the message object varies depending on the flow (e.g. OAuth or Email authentication flow, JWT or database sessions, etc). See the [events guide](/guides/basics/events) for more information on the form of each message object and how to use the events functions.
```js
events: {
async signIn(message) { /* on successful sign in */ },
async signOut(message) { /* on signout */ },
async createUser(message) { /* user created */ },
async updateUser(message) { /* user updated - e.g. their email was verified */ },
async linkAccount(message) { /* account (e.g. Twitter) linked to a user */ },
async session(message) { /* session is active */ },
}
```
---
### adapter
- **Default value**: none
- **Required**: _No_
#### Description
By default Auth.js does not include an adapter any longer. If you would like to persist user / account data, please install one of the many available adapters. More information can be found in the [adapter documentation](/reference/adapters/overview).
---
### debug
- **Default value**: `false`
- **Required**: _No_
#### Description
Set debug to `true` to enable debug messages for authentication and database operations.
---
### logger
- **Default value**: `console`
- **Required**: _No_
#### Description
Override any of the logger levels (`undefined` levels will use the built-in logger), and intercept logs in NextAuth. You can use this to send NextAuth logs to a third-party logging service.
The `code` parameter for `error` and `warn` are explained in the [Warnings](/reference/warnings) and [Errors](/reference/errors) pages respectively.
Example:
```js title="/pages/api/auth/[...nextauth].js"
import log from "logging-service"
export default NextAuth({
...
logger: {
error(code, metadata) {
log.error(code, metadata)
},
warn(code) {
log.warn(code)
},
debug(code, metadata) {
log.debug(code, metadata)
}
}
...
})
```
<Callout>
If the `debug` level is defined by the user, it will be called regardless of
the `debug: false` [option](#debug).
</Callout>
---
### theme
- **Default value**: `object`
- **Required**: _No_
#### Description
Changes the color scheme theme of [pages](/reference/configuration/auth-config#pages) as well as allows some minor customization. Set `theme.colorScheme` to `"light"`, if you want to force pages to always be light. Set to `"dark"`, if you want to force pages to always be dark. Set to `"auto"`, (or leave this option out) if you want the pages to follow the preferred system theme. (Uses the [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query.)
In addition, you can define a logo URL in `theme.logo` which will be rendered above the main card in the default signin/signout/error/verify-request pages, as well as a `theme.brandColor` which will affect the accent color of these pages.
```js
theme: {
colorScheme: "auto", // "auto" | "dark" | "light"
brandColor: "", // Hex color code
logo: "" // Absolute URL to image
}
```
---
## Advanced Options
Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.
---
### useSecureCookies
- **Default value**: `true` for HTTPS sites / `false` for HTTP sites
- **Required**: _No_
#### Description
When set to `true` (the default for all site URLs that start with `https://`) then all cookies set by Auth.js will only be accessible from HTTPS URLs.
This option defaults to `false` on URLs that start with `http://` (e.g. `http://localhost:3000`) for developer convenience.
<Callout>
Properties on any custom `cookies` that are specified override this option.
</Callout>
<Callout type="warning">
Setting this option to _false_ in production is a security risk and may allow
sessions to be hijacked if used in production. It is intended to support
development and testing. Using this option is not recommended.
</Callout>
---
### cookies
- **Default value**: `{}`
- **Required**: _No_
#### Description
Cookies in Auth.js are chunked by default, meaning that once they reach the 4kb limit, we will create a new cookie with the `.{number}` suffix and reassemble the cookies in the correct order when parsing / reading them. This was introduced to avoid size constraints which can occur when users want to store additional data in their sessionToken, for example.
You can override the default cookie names and options for any of the cookies used by Auth.js.
This is an advanced option and using it is not recommended as you may break authentication or introduce security flaws into your application.
You can specify one or more cookies with custom properties, but if you specify custom options for a cookie you must provide all the options for that cookie.
If you use this feature, you will likely want to create conditional behaviour to support setting different cookies policies in development and production builds, as you will be opting out of the built-in dynamic policy.
<Callout>
An example of a use case for this option is to support sharing session tokens
across subdomains.
</Callout>
#### Example
```js
cookies: {
sessionToken: {
name: `__Secure-next-auth.session-token`,
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: true
}
},
callbackUrl: {
name: `__Secure-next-auth.callback-url`,
options: {
sameSite: 'lax',
path: '/',
secure: true
}
},
csrfToken: {
name: `__Host-next-auth.csrf-token`,
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: true
}
},
pkceCodeVerifier: {
name: `${cookiePrefix}next-auth.pkce.code_verifier`,
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: useSecureCookies,
maxAge: 900
}
},
state: {
name: `${cookiePrefix}next-auth.state`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: useSecureCookies,
maxAge: 900
},
},
}
```
<Callout type="warning">
Using a custom cookie policy may introduce security flaws into your
application and is intended as an option for advanced users who understand the
implications. Using this option is not recommended.
</Callout>

View File

@@ -0,0 +1,40 @@
---
title: Environment variables
sidebar_label: Environment Variables
---
import { Callout } from "nextra-theme-docs"
## NEXTAUTH_URL
When deploying to production, set the `NEXTAUTH_URL` environment variable to the canonical URL of your site.
```
NEXTAUTH_URL=https://example.com
```
If your Next.js application uses a custom base path, specify the route to the API endpoint in full.
_e.g. `NEXTAUTH_URL=https://example.com/custom-route/api/auth`_
<Callout>
Using [System Environment Variables](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables) we automatically detect when you deploy to [Vercel](https://vercel.com) so you don't have to define this variable. Make sure **Automatically expose System Environment Variables** is checked in your Project Settings.
</Callout>
---
## NEXTAUTH_SECRET
Used to encrypt the Auth.js JWT, and to hash [email verification tokens](/reference/adapters/models#verification-token). This is the default value for the [`secret`](/reference/configuration/auth-config#secret) option. The `secret` option might be removed in the future in favor of this.
If you are using [Middleware](/reference/nextjs/#prerequisites) this environment variable must be set.
---
## NEXTAUTH_URL_INTERNAL
If provided, server-side calls will use this instead of `NEXTAUTH_URL`. Useful in environments when the server doesn't have access to the canonical URL of your site. Defaults to `NEXTAUTH_URL`.
```
NEXTAUTH_URL_INTERNAL=http://10.240.8.16
```

View File

@@ -0,0 +1,25 @@
---
title: Overview
sidebar_label: Overview
sidebar_position: 0
---
## Core
## Providers
- OAuth/OIDC
- Email/Passwordless
- Credentials
## Database Adapters
## Frameworks
- Next.js
- SvelteKit
- SolidStart
- Remix
- Nuxt
- Gatsby
- etc.

View File

@@ -0,0 +1,7 @@
---
title: Client
---
:::warning WIP
`@auth/nextjs/client` is work in progress. For now, please use [NextAuth.js Client API](https://next-auth.js.org/getting-started/client).
:::

View File

@@ -0,0 +1,7 @@
---
title: Next.js Auth
---
:::warning WIP
`@auth/nextjs` is work in progress. For now, please use [NextAuth.js](https://next-auth.js.org).
:::

View File

@@ -0,0 +1,40 @@
---
id: 42-school
title: 42 School
---
import { Callout } from "nextra-theme-docs"
<Callout>
42 returns a field on `Account` called `created_at` which is a number. See the [docs](https://api.intra.42.fr/apidoc/guides/getting_started#make-basic-requests). Make sure to add this field to your database schema, in case if you are using an [Adapter](/reference/adapters/overview).
</Callout>
## Documentation
https://api.intra.42.fr/apidoc/guides/web_application_flow
## Configuration
https://profile.intra.42.fr/oauth/applications/new
## Options
The **42 School Provider** comes with a set of default options:
- [42 School Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/42-school.ts)
You can override any of the options to suit your own use case.
## Example
```js
import FortyTwoProvider from "next-auth/providers/42-school";
...
providers: [
FortyTwoProvider({
clientId: process.env.FORTY_TWO_CLIENT_ID,
clientSecret: process.env.FORTY_TWO_CLIENT_SECRET
})
]
...
```

View File

@@ -0,0 +1,139 @@
---
id: apple
title: Apple
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://developer.apple.com/sign-in-with-apple/get-started/
## Configuration
https://developer.apple.com/account/resources/identifiers/list/serviceId
## Options
The **Apple Provider** comes with a set of default options:
- [Apple Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/apple.ts)
You can override any of the options to suit your own use case.
### Generating a secret
Apple requires the client secret to be a JWT. To generate one, you can use the following script: https://bal.so/apple-gen-secret.
For more information, see the [Apple docs](https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens#3262048)
Then, you can paste the result into your `.env.local` file under `APPLE_SECRET`, so you can refer to it from your code:
```js
import AppleProvider from "next-auth/providers/apple";
...
providers: [
AppleProvider({
clientId: process.env.APPLE_ID,
clientSecret: process.env.APPLE_SECRET
})
]
...
```
<Callout>
The TeamID is located on the top right after logging in.
</Callout>
<Callout>
The KeyID is located after you create the key. Look for it before you download the k8 file.
</Callout>
## Testing on a development server
<Callout>
Apple requires all sites to run HTTPS (including local development instances).
</Callout>
<Callout>
Apple doesn't allow you to use localhost in domains or subdomains.
</Callout>
### Host name resolution
Edit your host file and point your site to `127.0.0.1`.
_Linux/macOS_
```
sudo echo '127.0.0.1 dev.example.com' >> /etc/hosts
```
_Windows_ (run PowerShell as administrator)
```ps
Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value "127.0.0.1 dev.example.com" -Force
```
More info: [How to edit my host file?](https://phoenixnap.com/kb/how-to-edit-hosts-file-in-windows-mac-or-linux)
### Create certificate
Create a directory `certificates` and add the certificate files `localhost.key` and `localhost.crt`, which you generate using OpenSSL:
_Linux/macOS_
```bash
openssl req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj "/CN=localhost" -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")
```
_Windows_
The OpenSSL executable is distributed with [Git](https://git-scm.com/download/win) for Windows. Once installed you will find the openssl.exe file in `C:\Program Files\Git\mingw64\bin`, which you can add to the system PATH environment variable if its not already done.
Add environment variable `OPENSSL_CONF=C:\Program Files\Git\mingw64\ssl\openssl.cnf`
```cmd
req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj "/CN=localhost"
```
### Deploy to server
You can create a `server.js` in the root of your project and run it with `node server.js` to test Sign in with Apple integration locally:
```js
const { createServer } = require("https")
const { parse } = require("url")
const next = require("next")
const fs = require("fs")
const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()
const httpsOptions = {
key: fs.readFileSync("./certificates/localhost.key"),
cert: fs.readFileSync("./certificates/localhost.crt"),
}
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(3000, (err) => {
if (err) throw err
console.log("> Ready on https://localhost:3000")
})
})
```
### Helpful guides
- [How to setup localhost with HTTPS with a Next.js app](https://medium.com/@anMagpie/secure-your-local-development-server-with-https-next-js-81ac6b8b3d68)
- [Guide to configuring Sign in with Apple](https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple)

View File

@@ -0,0 +1,54 @@
---
id: atlassian
title: Atlassian
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://developer.atlassian.com/cloud/jira/platform/oauth-2-authorization-code-grants-3lo-for-apps/#implementing-oauth-2-0--3lo-
## Options
The **Atlassian Provider** comes with a set of default options:
- [Atlassian Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/atlassian.ts)
You can override any of the options to suit your own use case.
## Example
```js
import AtlassianProvider from "next-auth/providers/atlassian";
...
providers: [
AtlassianProvider({
clientId: process.env.ATLASSIAN_CLIENT_ID,
clientSecret: process.env.ATLASSIAN_CLIENT_SECRET,
authorization: {
params: {
scope: "write:jira-work read:jira-work read:jira-user offline_access read:me"
}
}
})
]
...
```
## Instructions
### Configuration
<Callout>
An app can be created at https://developer.atlassian.com/apps/
</Callout>
Under "Apis and features" in the side menu, configure the following for "OAuth 2.0 (3LO)":
- Redirect URL
- http://localhost:3000/api/auth/callback/atlassian
<Callout type="warning">
To enable access to Jira Platform REST API you must enable User Identity API and add `read:me` to your provider scope option.
</Callout>

View File

@@ -0,0 +1,41 @@
---
id: auth0
title: Auth0
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://auth0.com/docs/api/authentication#authorize-application
## Configuration
https://manage.auth0.com/dashboard
## Options
The **Auth0 Provider** comes with a set of default options:
- [Auth0 Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/auth0.ts)
You can override any of the options to suit your own use case.
## Example
```js
import Auth0Provider from "next-auth/providers/auth0";
...
providers: [
Auth0Provider({
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
issuer: process.env.AUTH0_ISSUER
})
]
...
```
<Callout>
`issuer` should be the fully qualified URL  e.g. `https://dev-s6clz2lv.eu.auth0.com`
</Callout>

View File

@@ -0,0 +1,37 @@
---
id: authentik
title: Authentik
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://goauthentik.io/docs/providers/oauth2
## Options
The **Authentik Provider** comes with a set of default options:
- [Authentik Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/authentik.ts)
You can override any of the options to suit your own use case.
## Example
```js
import AuthentikProvider from "next-auth/providers/authentik";
...
providers: [
AuthentikProvider({
clientId: process.env.AUTHENTIK_ID,
clientSecret: process.env.AUTHENTIK_SECRET,
issuer: process.env.AUTHENTIK_ISSUER,
})
]
...
```
<Callout>
`issuer` should include the slug without a trailing slash  e.g., `https://my-authentik-domain.com/application/o/My_Slug`
</Callout>

View File

@@ -0,0 +1,119 @@
---
id: azure-ad-b2c
title: Azure Active Directory B2C
---
import { Callout } from "nextra-theme-docs"
<Callout>
Azure AD B2C returns the following fields on `Account`:
- `refresh_token_expires_in` (number)
- `not_before` (number)
- `id_token_expires_in` (number)
- `profile_info` (string).
See their [docs](https://docs.microsoft.com/en-us/azure/active-directory-b2c/access-tokens). Remember to add these fields to your database schema, in case if you are using an [Adapter](/reference/adapters/overview).
</Callout>
## Documentation
https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow
## Configuration
https://docs.microsoft.com/azure/active-directory-b2c/tutorial-create-tenant
## Options
The **Azure Active Directory Provider** comes with a set of default options:
- [Azure Active Directory Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/azure-ad-b2c.ts)
You can override any of the options to suit your own use case.
## Configuration (Basic)
Basic configuration sets up Azure AD B2C to return an ID Token. This should be done as a prerequisite prior to running through the Advanced configuration.
Step 1: Azure AD B2C Tenant
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenant
Step 2: App Registration
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications
Step 3: User Flow
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows
Note: For the step "User attributes and token claims" you might minimally:
- Collect attribute:
- Email Address
- Display Name
- Given Name
- Surname
- Return claim:
- Email Addresses
- Display Name
- Given Name
- Surname
- Identity Provider
- Identity Provider Access Token
- User's Object ID
## Example
In `.env.local` create the following entries:
```
AZURE_AD_B2C_TENANT_NAME=<copy the B2C tenant name here from Step 1>
AZURE_AD_B2C_CLIENT_ID=<copy Application (client) ID here from Step 2>
AZURE_AD_B2C_CLIENT_SECRET=<copy generated secret value here from Step 2>
AZURE_AD_B2C_PRIMARY_USER_FLOW=<copy the name of the signin user flow you created from Step 3>
```
In `pages/api/auth/[...nextauth].js` find or add the AZURE_AD_B2C entries:
```js
import AzureADB2CProvider from "next-auth/providers/azure-ad-b2c";
...
providers: [
AzureADB2CProvider({
tenantId: process.env.AZURE_AD_B2C_TENANT_NAME,
clientId: process.env.AZURE_AD_B2C_CLIENT_ID,
clientSecret: process.env.AZURE_AD_B2C_CLIENT_SECRET,
primaryUserFlow: process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW,
authorization: { params: { scope: "offline_access openid" } },
}),
]
...
```
## Configuration (Advanced)
Advanced configuration sets up Azure AD B2C to return an Authorization Token. This builds on the steps completed in the Basic configuration above.
Step 4: Add a Web API application
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-single-page-app-webapi?tabs=app-reg-ga
Note: this is a second app registration (similar to Step 2) but with different setup and configuration.
## Example
Nothing in `.env.local` needs to change here. The only update is in `pages/api/auth/[...nextauth].js` where you will need to add the additional scopes that were created in Step 4 above:
```js
import AzureADB2CProvider from "next-auth/providers/azure-ad-b2c";
...
providers: [
AzureADB2CProvider({
tenantId: process.env.AZURE_AD_B2C_TENANT_NAME,
clientId: process.env.AZURE_AD_B2C_CLIENT_ID,
clientSecret: process.env.AZURE_AD_B2C_CLIENT_SECRET,
primaryUserFlow: process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW,
authorization: { params: { scope: `https://${process.env.AZURE_AD_B2C_TENANT_NAME}.onmicrosoft.com/api/demo.read https://${process.env.AZURE_AD_B2C_TENANT_NAME}.onmicrosoft.com/api/demo.write offline_access openid` } },
}),
]
...
```

View File

@@ -0,0 +1,61 @@
---
id: azure-ad
title: Azure Active Directory
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
## Configuration
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
## Example
### To allow specific Active Directory users access:
- In https://portal.azure.com/ search for "Azure Active Directory", and select your organization.
- Next, go to "App Registration" in the left menu, and create a new one.
- Pay close attention to "Who can use this application or access this API?"
- This allows you to scope access to specific types of user accounts
- Only your tenant, all azure tenants, or all azure tenants and public Microsoft accounts (Skype, Xbox, Outlook.com, etc.)
- When asked for a redirection URL, use `https://yourapplication.com/api/auth/callback/azure-ad` or for development `http://localhost:3000/api/auth/callback/azure-ad`.
- After your App Registration is created, under "Client Credential" create your Client secret.
- Now copy your:
- Application (client) ID
- Directory (tenant) ID
- Client secret (value)
In `.env.local` create the following entries:
```
AZURE_AD_CLIENT_ID=<copy Application (client) ID here>
AZURE_AD_CLIENT_SECRET=<copy generated client secret value here>
AZURE_AD_TENANT_ID=<copy the tenant id here>
```
That will default the tenant to use the `common` authorization endpoint. [For more details see here](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints).
<Callout>
Azure AD returns the profile picture in an ArrayBuffer, instead of just a URL to the image, so our provider converts it to a base64 encoded image string and returns that instead. See: https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0#examples. The default image size is 48x48 to avoid [running out of space](https://authjs.dev/concepts/faq#:~:text=What%20are%20the%20disadvantages%20of%20JSON%20Web%20Tokens%3F) in case the session is saved as a JWT.
</Callout>
In `pages/api/auth/[...nextauth].js` find or add the `AzureAD` entries:
```js
import AzureADProvider from "next-auth/providers/azure-ad";
...
providers: [
AzureADProvider({
clientId: process.env.AZURE_AD_CLIENT_ID,
clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
tenantId: process.env.AZURE_AD_TENANT_ID,
}),
]
...
```

View File

@@ -0,0 +1,46 @@
---
id: battle.net
title: Battle.net
---
## Documentation
https://develop.battle.net/documentation/guides/using-oauth
## Configuration
https://develop.battle.net/access/clients
## Options
The **Battle.net Provider** comes with a set of default options:
- [Battle.net Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/battlenet.ts)
You can override any of the options to suit your own use case.
## Example
```js
import BattleNetProvider from "next-auth/providers/battlenet";
...
providers: [
BattleNetProvider({
clientId: process.env.BATTLENET_CLIENT_ID,
clientSecret: process.env.BATTLENET_CLIENT_SECRET,
issuer: process.env.BATTLENET_ISSUER
})
]
...
```
`issuer` must be one of these values, based on the [available regions](https://develop.battle.net/documentation/guides/regionality-and-apis):
```ts
type BattleNetIssuer =
| "https://www.battlenet.com.cn/oauth"
| "https://us.battle.net/oauth"
| "https://eu.battle.net/oauth"
| "https://kr.battle.net/oauth"
| "https://tw.battle.net/oauth"
```

View File

@@ -0,0 +1,34 @@
---
id: box
title: Box
---
## Documentation
https://developer.box.com/reference/
## Configuration
https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/configure-box/
## Options
The **Box Provider** comes with a set of default options:
- [Box Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/box.js)
You can override any of the options to suit your own use case.
## Example
```js
import BoxProvider from "next-auth/providers/box";
...
providers: [
BoxProvider({
clientId: process.env.BOX_CLIENT_ID,
clientSecret: process.env.BOX_CLIENT_SECRET
})
]
...
```

View File

@@ -0,0 +1,58 @@
---
id: boxyhq-saml
title: BoxyHQ SAML
---
## Documentation
BoxyHQ SAML is an open source service that handles the SAML login flow as an OAuth 2.0 flow, abstracting away all the complexities of the SAML protocol.
You can deploy BoxyHQ SAML as a separate service or embed it into your app using our NPM library. [Check out the documentation for more details](https://boxyhq.com/docs/jackson/deploy)
## Configuration
SAML login requires a configuration for every tenant of yours. One common method is to use the domain for an email address to figure out which tenant they belong to. You can also use a unique tenant ID (string) from your backend for this, typically some kind of account or organization ID.
Check out the [documentation](https://boxyhq.com/docs/jackson/saml-flow#2-saml-config-api) for more details.
## Options
The **BoxyHQ SAML Provider** comes with a set of default options:
- [BoxyHQ Provider options](https://github.com/nextauthjs/next-auth/tree/main/packages/next-auth/src/providers/boxyhq-saml.ts)
You can override any of the options to suit your own use case.
## Example
```ts
import BoxyHQSAMLProvider from "next-auth/providers/boxyhq-saml"
...
providers: [
BoxyHQSAMLProvider({
issuer: "http://localhost:5225",
clientId: "dummy", // The dummy here is necessary since we'll pass tenant and product custom attributes in the client code
clientSecret: "dummy", // The dummy here is necessary since we'll pass tenant and product custom attributes in the client code
})
}
...
```
On the client side you'll need to pass additional parameters `tenant` and `product` to the `signIn` function. This will allow BoxyHQL SAML to figure out the right SAML configuration and take your user to the right SAML Identity Provider to sign them in.
```tsx
import { signIn } from "next-auth/react";
...
// Map your users's email to a tenant and product
const tenant = email.split("@")[1];
const product = 'my_awesome_product';
...
<Button
onClick={async (event) => {
event.preventDefault();
signIn("boxyhq-saml", {}, { tenant, product });
}}>
...
```

View File

@@ -0,0 +1,139 @@
---
id: bungie
title: Bungie
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://github.com/Bungie-net/api/wiki/OAuth-Documentation
## Configuration
https://www.bungie.net/en/Application
## Options
The **Bungie Provider** comes with a set of default options:
- [Bungie Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/bungie.js)
You can override any of the options to suit your own use case.
## Example
```js
import BungieProvider from "next-auth/providers/bungie";
...
providers: [
BungieProvider({
clientId: process.env.BUNGIE_CLIENT_ID,
clientSecret: process.env.BUNGIE_SECRET,
headers: {
"X-API-Key": process.env.BUNGIE_API_KEY
}
}),
]
...
```
### Configuration
<Callout>
Bungie require all sites to run HTTPS (including local development instances).
</Callout>
<Callout>
Bungie doesn't allow you to use localhost as the website URL, instead you need to use https://127.0.0.1:3000
</Callout>
Navigate to https://www.bungie.net/en/Application and fill in the required details:
- Application name
- Application Status
- Website
- OAuth Client Type
- Confidential
- Redirect URL
- https://localhost:3000/api/auth/callback/bungie
- Scope
- `Access items like your Bungie.net notifications, memberships, and recent Bungie.Net forum activity.`
- Origin Header
The following guide may be helpful:
- [How to setup localhost with HTTPS with a Next.js app](https://medium.com/@anMagpie/secure-your-local-development-server-with-https-next-js-81ac6b8b3d68)
### Example server
You will need to edit your host file and point your site at `127.0.0.1`
[How to edit my host file?](https://phoenixnap.com/kb/how-to-edit-hosts-file-in-windows-mac-or-linux)
On Windows (Run Powershell as administrator)
```ps
Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value "127.0.0.1`tdev.example.com" -Force
```
```
127.0.0.1 dev.example.com
```
#### Create certificate
Creating a certificate for localhost is easy with openssl. Just put the following command in the terminal. The output will be two files: localhost.key and localhost.crt.
```bash
openssl req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj "/CN=localhost" -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")
```
<Callout>
**Windows**
The OpenSSL executable is distributed with [Git](https://git-scm.com/download/win]9) for Windows.
Once installed you will find the openssl.exe file in `C:/Program Files/Git/mingw64/bin` which you can add to the system PATH environment variable if its not already done.
Add environment variable `OPENSSL_CONF=C:/Program Files/Git/mingw64/ssl/openssl.cnf`
```bash
req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj "/CN=localhost"
```
</Callout>
Create directory `certificates` and place `localhost.key` and `localhost.crt`
You can create a `server.js` in the root of your project and run it with `node server.js` to test Sign in with Bungie integration locally:
```js
const { createServer } = require("https")
const { parse } = require("url")
const next = require("next")
const fs = require("fs")
const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()
const httpsOptions = {
key: fs.readFileSync("./certificates/localhost.key"),
cert: fs.readFileSync("./certificates/localhost.crt"),
}
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(3000, (err) => {
if (err) throw err
console.log("> Ready on https://localhost:3000")
})
})
```

View File

@@ -0,0 +1,51 @@
---
id: cognito
title: Amazon Cognito
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html
## Configuration
https://console.aws.amazon.com/cognito/users/
You need to select your AWS region to go the the Cognito dashboard.
## Options
The **Amazon Cognito Provider** comes with a set of default options:
- [Amazon Cognito Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/cognito.ts)
You can override any of the options to suit your own use case.
## Example
```js
import CognitoProvider from "next-auth/providers/cognito";
...
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_ISSUER,
})
]
...
```
<Callout>
The issuer is a URL, that looks like this: `https://cognito-idp.{region}.amazonaws.com/{PoolId}`
</Callout>
`PoolId` is from `General Settings` in Cognito, not to be confused with the App Client ID.
<Callout type="warning">
Make sure you select all the appropriate client settings or the OAuth flow will not work.
</Callout>
![cognito](https://user-images.githubusercontent.com/7902980/83951604-cd096e80-a832-11ea-8bd2-c496ec9a16cb.PNG)

View File

@@ -0,0 +1,40 @@
---
id: coinbase
title: Coinbase
---
import { Callout } from "nextra-theme-docs"
## Documentation
https://developers.coinbase.com/api/v2
## Configuration
https://www.coinbase.com/settings/api
## Options
The **Coinbase Provider** comes with a set of default options:
- [Coinbase Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/coinbase.js)
You can override any of the options to suit your own use case.
## Example
```js
import CoinbaseProvider from "next-auth/providers/coinbase";
...
providers: [
CoinbaseProvider({
clientId: process.env.COINBASE_CLIENT_ID,
clientSecret: process.env.COINBASE_CLIENT_SECRET
})
]
...
```
<Callout>
This Provider template has a 2 hour access token to it. A refresh token is also returned.
</Callout>

View File

@@ -0,0 +1,34 @@
---
id: discord
title: Discord
---
## Documentation
https://discord.com/developers/docs/topics/oauth2
## Configuration
https://discord.com/developers/applications
## Options
The **Discord Provider** comes with a set of default options:
- [Discord Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/discord.ts)
You can override any of the options to suit your own use case.
## Example
```js
import DiscordProvider from "next-auth/providers/discord";
...
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET
})
]
...
```

View File

@@ -0,0 +1,34 @@
---
id: dropbox
title: Dropbox
---
## Documentation
https://developers.dropbox.com/oauth-guide
## Configuration
https://www.dropbox.com/developers/apps
## Options
The **Dropbox Provider** comes with a set of default options:
- [Dropbox Provider options](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/providers/dropbox.js)
You can override any of the options to suit your own use case.
## Example
```js
import DropboxProvider from "next-auth/providers/dropbox";
...
providers: [
DropboxProvider({
clientId: process.env.DROPBOX_CLIENT_ID,
clientSecret: process.env.DROPBOX_CLIENT_SECRET
})
]
...
```

Some files were not shown because too many files have changed in this diff Show More