Compare commits

...

242 Commits

Author SHA1 Message Date
Lluis Agusti
5d815ce593 chore: wip 2023-04-16 23:28:54 +09:00
Lluis Agusti
25be00b749 Merge 'main' into 'docs/providers-to-source-code' 2023-04-14 13:46:47 +09:00
Balázs Orbán
b31f2af66c feat: misc improvements (#7228)
* tweak types, fix typos

* filter non-oauth files when generating provider types

* allow implicit config invoke

* remove workaround for multiple cookie settings in Next.js

* feat: return `null` when session does not exist

* error on missing checks when configured
2023-04-12 11:40:55 +01:00
Prana Adiwira
71bb6f2590 fix(providers): Use the proper check for Reddit (#7224)
Reddit expects the `state` parameter

https://github.com/reddit-archive/reddit/wiki/OAuth2#authorization
2023-04-12 11:37:31 +01:00
Lluis Agusti
f28b58d49d chore: wip 2023-04-10 21:23:27 +09:00
Balázs Orbán
6c07331cc5 chore: upgrade turbo 2023-04-06 12:58:10 +02:00
Saurav Maheshkar
c8ef94b2be chore: move prettier and eslint configs under package.json (#7145) 2023-04-06 12:57:16 +02:00
jakzo
75a59fbd92 chore(docs): fix dynamodb typo (#7130)
fix: typo
2023-04-06 12:57:09 +02:00
Balázs Orbán
3dd47b0735 docs(example): remove unstable_ prefix 2023-03-31 05:01:58 +02:00
Balázs Orbán
4dc1d421f8 docs: mention client in OAuth config options
Related issue #7114
2023-03-30 18:34:30 +02:00
Balázs Orbán
99ca67f1cf docs: fix typo 2023-03-28 13:59:08 +02:00
Balázs Orbán
a087df8494 docs: fix some links 2023-03-28 13:47:53 +02:00
Sai Srikar Dumpeti
1aa4994de6 docs: respect color scheme (#7076) 2023-03-28 04:06:21 +02:00
Alan Hoskins
88023f69b9 fix(docs): remove extra install (#7081) 2023-03-27 15:47:32 +02:00
Alan Hoskins
b02057a72d fix(docs): fix broken links links (#7083)
Co-authored-by: Alan Hoskins <ahoskins@knowland.com>
2023-03-27 15:46:43 +02:00
Balázs Orbán
400da8c766 fix(providers): mention Email Address as required for Azure B2C
closes #7071
2023-03-27 15:44:23 +02:00
Andres Rodriguez
b48104801b chore(provider): added svg for Reddit (#7050)
Added svg for Reddit

Co-authored-by: Nico Domino <yo@ndo.dev>
2023-03-27 09:36:47 +02:00
Balázs Orbán
ccbbc800d2 docs: rephrase buttons on landing page 2023-03-27 02:06:33 +02:00
Abdulaziz Askaraliev
d7888263ca fix(providers): update Yandex to TypeScript (#7054)
* fix(providers): yandex add typescript.

* fix(providers): yandex add avatar to scope

* fix(providers): Yandex - add types & avatar scope

* fix(providers): Yandex - permissions list

* Apply suggestions from code review

* Apply suggestions from code review

* docs(provider): added comments for

* revert yandex.ts from next-auth/providers/

* fix(providers): yandex fix typo

* revert

* Update [...nextauth].ts

* Update yandex.ts

* Update yandex.ts

* Update [...nextauth].ts

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-27 00:38:06 +01:00
Balázs Orbán
47d3151410 Merge branch 'main' of github.com:nextauthjs/next-auth 2023-03-27 01:32:54 +02:00
Balázs Orbán
7d264860ab chore: package builds as docs#dev task dependencies 2023-03-27 01:32:50 +02:00
Abdulaziz Askaraliev
6184b936f5 chore(docs): show close button on announcementBar (#7074)
* fix #6935: show close button.

* fix(global-css): show close button on annoucement bar

dev and build were generating different results, adding `!important` fixed on build.
2023-03-26 21:48:36 +02:00
Balázs Orbán
1954258a0a docs: make security page top-level 2023-03-26 03:46:51 +02:00
Jabed Zaman
c580f0db22 docs: fix session.user is possibly undefined. (#7058)
fixed the code snippet for the example to consume session via hooks. Threw an error earlier stating 'session.user' is possibly 'undefined'.
2023-03-25 20:15:38 +00:00
Balázs Orbán
d1cf701ed9 docs: change admonition titles 2023-03-24 12:46:02 +01:00
Balázs Orbán
69398e2d3a docs: clarify guides overview 2023-03-24 12:43:56 +01:00
Balázs Orbán
856b5c50fc docs: change section title 2023-03-24 12:43:40 +01:00
Balázs Orbán
2830b7de5b docs: fix some typos 2023-03-24 12:43:23 +01:00
Balázs Orbán
40a0faa586 docs: remove outdated guides 2023-03-24 12:43:08 +01:00
Balázs Orbán
a6b4d958ac docs: open basics guides by default 2023-03-24 12:42:52 +01:00
Balázs Orbán
cc13df9d51 docs: tweak announcement bar 2023-03-24 12:42:41 +01:00
Balázs Orbán
06b8d4772c docs: simplify 2023-03-24 03:44:59 +01:00
Balázs Orbán
d644d1fcbf docs: add sidebar to API reference 2023-03-24 03:43:15 +01:00
Balázs Orbán
380f2de961 docs: add API reference overview 2023-03-24 03:29:29 +01:00
Nikhil Dev Chunchu
dc5f3e1873 chore(docs): update using-a-database-adapter.md (#7028)
Update using-a-database-adapter.md
2023-03-22 09:30:56 +01:00
Balázs Orbán
93f3fcd1b7 chore: update TypeDoc 2023-03-21 19:38:50 +01:00
Lluis Agusti
1d9b9ba47c docs(adapters): source content + overview (#7023)
* docs(adapters): source content + overview

* Apply suggestions from code review

* add adapter packages as docs dependencies

* clean up docusaurus config

* clean up database overview

* fix some links

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-21 18:26:52 +00:00
Balázs Orbán
8f6108f230 docs: fix Mermaid rendering, lock gatsby playground versions 2023-03-21 18:54:10 +01:00
Balázs Orbán
15943d6696 docs: fix indent 2023-03-21 01:02:20 +01:00
Balázs Orbán
81589bf738 docs: remove/rename files/directories 2023-03-21 00:49:39 +01:00
Balázs Orbán
09402bf2fc fix: correct logo link 2023-03-20 22:45:14 +01:00
Balázs Orbán
e39a968a7b fix: correct logo link 2023-03-20 22:38:00 +01:00
Balázs Orbán
b03378be7f fix: correct links 2023-03-20 22:37:27 +01:00
Balázs Orbán
af415e9438 fix: correct link 2023-03-20 22:31:12 +01:00
Balázs Orbán
90eeeeab2f docs: unify adapters (#7013)
* remove unmaintained changelogs

* move logos to docs

* unify readmes

* fix logo urls
2023-03-20 21:28:23 +00:00
Balázs Orbán
f0b475fc72 docs: move adapters sidebar around 2023-03-20 21:59:19 +01:00
Balázs Orbán
f4f8c4a0b3 fix: links and references 2023-03-20 21:56:10 +01:00
Thang Vu
6f2cb460c9 feat: rewrite PouchDB Adapter (#6745)
BREAKING CHANGE:
Complete rewrite of the package. It is now published as ESM-only and written for `next-auth@4`. `next-auth@3` support is removed.

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-20 20:50:25 +00:00
Balázs Orbán
46f285f6f0 chore: fix test 2023-03-20 21:45:25 +01:00
Balázs Orbán
6bdb8af78d fix(test): export _id function for tests 2023-03-20 21:39:44 +01:00
James Billot
04e0637fd8 chore: fix typo in 'collectionsFactory' (#6985) 2023-03-20 17:47:38 +01:00
David Prothero
b5712448a1 fix(docs): correct module name (#6996) 2023-03-20 17:47:01 +01:00
Gabriel Manor
605d15c3cc docs: Add Permit.io Bronze Sponsor (#7008) 2023-03-20 17:42:11 +01:00
Anti Revoluzzer
d1479125cb fix: make nonce work correctly (#6998)
Co-authored-by: Anti Revoluzzer <anti@siimpl.io>
2023-03-20 12:07:11 +00:00
Abdulaziz Askaraliev
2e09bc0d19 docs: show close button (#7007) 2023-03-20 11:55:57 +00:00
Balázs Orbán
843fc6ff8f Merge branch 'main' of github.com:nextauthjs/next-auth 2023-03-20 12:51:22 +01:00
Balázs Orbán
6695ff8503 chore: add missing outputs to Turbo cache 2023-03-20 12:51:18 +01:00
Abdulaziz
80c1f375b8 docs: fix announcementBar fixed height cutting content inside itself (#6934) (#6975) 2023-03-16 11:53:01 +01:00
Abdulaziz
5a13288d47 docs: fix text overflow in li tags (#6973) 2023-03-16 11:52:13 +01:00
Balázs Orbán
26201e6271 chore: fix indentation 2023-03-16 02:23:46 +00:00
Balázs Orbán
d0d7b90ba1 chore: fix rm command 2023-03-16 02:59:16 +01:00
Balázs Orbán
874624dfbe fix(ts): fix type 2023-03-16 02:58:17 +01:00
Balázs Orbán
4b5cd08800 chore: add fauna adapter as docs dep 2023-03-16 02:53:30 +01:00
Lluis Agusti
1c104afef9 docs(fauna): move content to source (#6919)
* docs(fauna): move content to source

* chore: fix spelling

* Apply suggestions from code review

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-16 01:50:21 +00:00
Ólafur Waage
ff5b8ba8e2 fix(docs): Update documentation (#6956)
* Adding correct sveltekit client doc links.

* Updating urls for sveltekit index.
2023-03-16 01:02:27 +01:00
Jonas Strassel
42d5899efd fix(adapters): allow mongodb@5 as peer dependency (#6938) 2023-03-14 13:31:01 +01:00
Jonas Strassel
b278975c3f chore(ci): disable node cache to speed up ci (#6939) 2023-03-14 13:29:18 +01:00
Ábris Simon
997e595b5b fix(docs:) simplify authorization example (#6910)
* simplify authorization example for sveltekit

* Apply suggestions from code review

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-10 16:41:00 +00:00
Balázs Orbán
527c25b128 chore: add clean script to dynamodb adapter 2023-03-10 10:56:09 +01:00
Balázs Orbán
0e2bbda537 docs: remove duplicate API reference 2023-03-10 10:51:17 +01:00
Balázs Orbán
7f3b35593f chore: tweak turbo config 2023-03-10 10:37:47 +01:00
Lluis Agusti
bce6b00c43 docs(dynamodb): move content to source (#6903)
* chore: wip

* chore: done

* chore: fix

* update lock file

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-09 11:33:53 +00:00
Balázs Orbán
1bbd5d51d1 chore: add adapters as docs dependencies 2023-03-09 12:24:00 +01:00
Lluis Agusti
b24b02fe71 docs(mongodb): move content to source (#6901)
* docs(mongodb): move content to source

* chore: document options

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-09 11:22:54 +00:00
Lluis Agusti
2c5c4d18c4 docs(typeorm): move content to source (#6896)
* docs(typeorm): move content to source

* chore: fix fn

* chore: document options

* Update index.ts

* chore: update logo

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-09 11:20:04 +00:00
Balázs Orbán
e3f9b398f0 chore: add adapters to docs as dependencies 2023-03-09 12:00:19 +01:00
Balázs Orbán
ab13930020 chore: tweak turbo cache 2023-03-09 11:48:45 +01:00
Nico Domino
f6bb16b264 chore: update README sponsors - fusionauth level (#6892) 2023-03-08 16:54:54 +00:00
Nico Domino
a220245d03 chore(repo): add FusionAuth to README supporters (#6883)
* chore(repo): add FusionAuthu to README supporters

* chore(repo): put sponsors on two lines of 5
2023-03-07 08:53:25 +07:00
Lluis Agusti
7462e797de fix(adapter): improve Adapter docs, add runtime assertions (#6877)
* docs(adapters): move dgraph adapters docs to source code

* refactor: review suggestions (1)

* docs(prisma): move content to source code

* chore: sort

* fix: dgraph logo and content
2023-03-05 17:19:04 +01:00
Balázs Orbán
36286b1fae fix(adapter): improve Adapter docs, add runtime assertions (#6612)
* fix(ts): improve Adapter documentation

* chore: simplify code

* assert missing adapter methods

* add federated logout guide link

* oidc -> oauth
2023-03-05 15:39:23 +00:00
Nico Domino
2e8e90a9be chore(docs): new guide for sending email via http api (#6555)
* chore(docs): new guide for sending email via http api

* chore(docs): prettier code blocks

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* fix: relative links and remove prisma specific mention

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Update docs/docs/guides/04-providers/03-email-http-api.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* chore: reword to be more inclusive

* feat: use custom provider

* Apply suggestions from code review

* code review changes

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-03-05 15:32:08 +00:00
Balázs Orbán
d06a552bf6 chore: format 2023-03-05 16:07:51 +01:00
Lluis Agusti
5cb8dd5f37 fix(docs): add docs to source code (#6870)
* docs(adapters): move dgraph adapters docs to source code

* refactor: review suggestions (1)
2023-03-05 15:57:02 +01:00
GitHub Actions
7c1a3b547e chore(release): bump package version(s) [skip ci] 2023-03-05 05:08:02 +00:00
Josh Schlesser
2534ae8801 feat(sveltekit): allow dynamic authOptions (#6744)
* added optional dynamic sveltekit options

* changed dynamicOptions function to async

* converted dynamicOptions to a named type

* updated inline docs to show async capabilities

* Update packages/frameworks-sveltekit/src/lib/index.ts

Co-authored-by: Thang Vu <hi@thvu.dev>

* Update packages/frameworks-sveltekit/src/lib/index.ts

Co-authored-by: Thang Vu <hi@thvu.dev>

* Update packages/frameworks-sveltekit/src/lib/index.ts

Co-authored-by: Thang Vu <hi@thvu.dev>

* Update packages/frameworks-sveltekit/src/lib/index.ts

Co-authored-by: Thang Vu <hi@thvu.dev>

* Update packages/frameworks-sveltekit/src/lib/index.ts

Co-authored-by: Thang Vu <hi@thvu.dev>

* refined to a simpler function signature

* removed redundant return statement

* Apply suggestions from code review

---------

Co-authored-by: Thang Vu <hi@thvu.dev>
2023-03-04 12:21:14 +07:00
Thomas Guillet
14a120277b docs(sveltekit): Write the explicit file to update in sveltekit (#6846) 2023-03-01 09:31:30 +07:00
Josh Schlesser
c49f484743 fix(providers): add default user agent for GitHub (#6742)
See: https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#user-agent-required
2023-02-28 12:56:28 +01:00
Richard Tuin
676b39d5b1 docs: Improve naming on role based access (#6820) 2023-02-28 12:54:26 +01:00
Balázs Orbán
e27dbcab2f chore: tweak "incomplete" comment 2023-02-28 12:48:51 +01:00
Thang Vu
63805c7d75 fix: JWT maxAge default to Session maxAge value (#6829)
* fix: JWT maxAge default to Session maxAge value

Co-Authored-By: Ethan Wilkes <33569440+roberte777@users.noreply.github.com>

* Move to core

Co-Authored-By: Ethan Wilkes <33569440+roberte777@users.noreply.github.com>

---------

Co-authored-by: Ethan Wilkes <33569440+roberte777@users.noreply.github.com>
2023-02-27 08:30:14 +07:00
GitHub Actions
5d1c35e8aa chore(release): bump package version(s) [skip ci] 2023-02-24 14:20:38 +00:00
James Birtles
a77f557cbf fix: claims being serialized multiple times over (#6781) 2023-02-23 15:02:13 +01:00
Thang Vu
657492d921 docs: Improve Getting Started (#6551)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Lluis Agusti <hi@llu.lu>
2023-02-23 14:55:14 +01:00
Will
d1d63bddba chore: Add 🥈 Silver Financial Sponsors (#6757)
Add Silver Sponsors to the README
2023-02-23 11:32:48 +07:00
Will
99ac4899b5 feat(providers): add Beyond Identity Provider (#6013)
* Add Beyond Identity Provider

* Add Beyond Identity OIDC Provider

* Add Beyond Identity OIDC Provider

* Add "pkce" support

* Mirror Auth0 instead of Okta

* Code Review feedback
2023-02-23 11:04:21 +07:00
Balázs Orbán
2130765a57 docs: remove duplicate from sidebar 2023-02-19 17:13:06 +01:00
Balázs Orbán
4079274aaf fix(providers): document Azure AD B2C 2023-02-19 17:12:54 +01:00
OrJDev
3d7985fd6d fix: multiple set-cookie headers (#6749)
* fix: multiple set-cookie headers

* fx
2023-02-17 19:08:41 +01:00
Thang Vu
331e0ce51e fix(adapters): comply to Node.js native ESM resolver (#6753)
* fix(adapters): comply to Node.js native ESM resolver for Firebase adapter

* fix import

* use single file

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-02-17 14:39:06 +00:00
Balázs Orbán
8af666a4cc fix: correct package name 2023-02-17 13:05:40 +01:00
Jakob Norlin
fed0a67917 fix: compatibility with edge runtimes (#6739)
* Bump @panva/hkdf to v1.0.3

Fixes #6736

* Update to v1.0.4

v.1.0.3 failed to publish it seems

* update lockfile

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-02-17 11:24:17 +00:00
Erik André Jakobsen
0332d86942 docs: fix dead external prisma link (#6721)
A very minor change, but thought I would fix it when I saw it :)
2023-02-17 11:15:49 +00:00
Balázs Orbán
8b38d32430 docs: update refresh token guide
closes #6696
2023-02-13 13:44:40 +00:00
Balázs Orbán
1e5f840a26 chore: fix import
fixes #6699
2023-02-13 14:31:22 +01:00
Lioness100
5981712681 fix: address typos (#6701)
* docs: fix typos

* revert: typo fixes in packages/next-auth
2023-02-13 12:51:54 +00:00
Skyf0l
dd2b85c6a5 chore: add missing angle bracket in package.json contributors (#6698) 2023-02-12 21:01:56 +07:00
Balázs Orbán
3c0475acae fix(ts): fix typo in JSDoc 2023-02-10 02:18:08 +01:00
Balázs Orbán
416881c4c9 Merge branch 'main' of github.com:nextauthjs/next-auth 2023-02-10 02:10:30 +01:00
Balázs Orbán
b91167091c fix(ts): use default exports for all providers uniformly
closes #6615
2023-02-10 02:10:27 +01:00
JT A
497dacff41 docs: fix code example nesting (#6666)
While doing the Getting Started guide, we noticed that the configuration was incorrect.

cc: @obrowner-rdc
2023-02-10 01:51:29 +01:00
JT A
2a1e1d1cd2 docs: use correct env variable names (#6668)
The documentation had the incorrect environment variable names used in the configuration for `Email` provider.
2023-02-10 01:50:00 +01:00
Balázs Orbán
00f65b3476 docs: fix indent 2023-02-10 01:47:55 +01:00
Pavlos Vinieratos
470e55f8db docs: fix typo (#6674)
Update 02-oauth-tutorial.mdx
2023-02-10 01:42:43 +01:00
Balázs Orbán
d722962206 fix(ts): correct credentials types in authorize callback (#6648)
* fix(ts): correct `credentials` types in `authorize` callback

* Apply suggestions from code review

Co-authored-by: Thang Vu <hi@thvu.dev>

---------

Co-authored-by: Thang Vu <hi@thvu.dev>
2023-02-09 13:05:56 +01:00
AlandSleman
cee1bddbd5 docs: Fix Getting started page (#6636)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-02-07 15:08:29 +01:00
Rémi Robichet
e0ae913e5c docs: fix type import (#6638) 2023-02-07 15:06:48 +01:00
Thang Vu
1db27fcd07 chore(monorepo): cache docs/build 2023-02-06 10:03:32 +07:00
Thang Vu
95407df289 chore(monorepo): cache typedoc generated files 2023-02-06 09:54:36 +07:00
Balázs Orbán
22adc2eb3c docs: fix redirects 2023-02-06 00:04:44 +01:00
Balázs Orbán
725f976b39 docs: fix redirects 2023-02-06 00:03:28 +01:00
MatyiFKBT
28ae5d4639 fix(providers): update Foursquare API version (#6620) 2023-02-05 15:30:57 +01:00
GitHub Actions
0f4d43e9ad chore(release): bump package version(s) [skip ci] 2023-02-05 13:52:31 +00:00
Thang Vu
28583b8ab0 feat: drop crypto dependency, convert to ESM (#6603)
Co-authored-by: Balázs Orbán <info@balazsorban.com>

BREAKING CHANGE:
- This package now only ships ESM, as all maintained Node.js versions have native support
- Dropped the `crypto` Node.js import in favor of `uuid`. When `globalThis.crypto` is the default in the future, we can remove `uuid` again
2023-02-05 14:44:33 +01:00
Balázs Orbán
1e7538a955 fix: publish .d.ts.map, add experimental warning 2023-02-05 14:42:07 +01:00
Wyatt Ades
4258857e52 feat(adapters): move to firebase-admin in Firebase Adapter (#6225)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
fixes https://github.com/nextauthjs/next-auth/issues/5049
closes https://github.com/nextauthjs/next-auth/pull/6230
closes https://github.com/nextauthjs/next-auth/pull/5449
closes https://github.com/nextauthjs/next-auth/pull/5055
fixes https://github.com/nextauthjs/next-auth/issues/4927

BREAKING CHANGE:
The adapter now expects `firebase-admin` instead of the `firebase` package and also supports either passing a config object or a firestore instance.
2023-02-05 14:41:20 +01:00
Balázs Orbán
e9d8805609 docs: api reference restructure (#6608) 2023-02-04 15:39:12 +01:00
Mayvis
fb43c5da05 docs: enhance prisma mongodb doc to prevent warning (#6598)
Fixes https://github.com/nextauthjs/next-auth/issues/6597
2023-02-02 13:28:17 +01:00
Corey Jepperson
326eadf0ed fix: don't add /error to url pathname when email verification is successful (#6492)
fix handleAuthorized making bad pth when authorize

Co-authored-by: Corey Jepperson <corey@entropy.cc>
Co-authored-by: Thang Vu <hi@thvu.dev>
2023-01-31 17:37:38 +07:00
Thang Vu
a5e0db4bb3 feat(providers): add Notion provider (#6567)
* add notion provider along with logo and styles
"

* adjust notion documentation

* update issue template with Notion provider

* update docs and provider with code from TomYeoman

* feat: move Notion provider to core

* get it working

---------

Co-authored-by: Harrison Broadbent <harrisonbroadbent@gmail.com>
Co-authored-by: Harrison Broadbent <harrisonbroadbent@Harrisons-MacBook-Air.local>
Co-authored-by: Thang Vu <hi@thvu.dev>
2023-01-31 17:10:47 +07:00
Balázs Orbán
334e23343a chore: fix typo 2023-01-31 01:19:16 +01:00
OrJDev
be046a6cb2 chore: suggest using the correct command to seek for packages (#6570)
* fix: suggest using the correct command to seek for packages

* seek for adapter packages aswell

* cleanup: seek for auth org packages
2023-01-30 20:39:37 +01:00
Frank Dumont
bdee262abe fix: typo in log message (#6569) 2023-01-30 20:37:53 +01:00
Balázs Orbán
3f89e668ec fix(ts): mark options provider config option internal (#6564)
* chore(dev): use workspace modules in Svelte app

* fix(ts): mark `options` provider config option internal
2023-01-30 12:34:54 +00:00
Balázs Orbán
533320eb94 chore: generate oauth-types on build 2023-01-29 14:33:41 +01:00
James
dfe6509472 fix: comment Discord profile, fix @auth/sveltekit build on Windows (#6550)
* fix: discord types were inaccurate

* fix: build on windows computers

* Apply review suggestions

* Update discord.ts

---------

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-29 12:05:14 +00:00
Oskar
1bde7cc8df fix(core): correct docs link (#6446) 2023-01-26 12:16:47 +00:00
Balázs Orbán
cef05d5e2d Merge branch 'main' of github.com:nextauthjs/next-auth 2023-01-26 13:11:14 +01:00
Balázs Orbán
c0dea283ba fix(core): avoid circular dependency
Fixes #6508
2023-01-26 13:11:04 +01:00
Balázs Orbán
0204766e0f fix(core): don't lock nodemailer version as peer dependency 2023-01-25 14:29:16 +00:00
Jérémie Sellam
a336ba762c fix(adapters): allow already initialized firebase app 🐛 (#6230)
* 🐛 Fix already initialized firebase app

* remove comment

Co-authored-by: Jérémie Sellam <jeremie@southpigalle.io>
Co-authored-by: Thang Vu <hi@thvu.dev>
2023-01-25 19:57:52 +07:00
Balázs Orbán
681d53c2f8 chore(core): cleanup 2023-01-24 14:01:40 +01:00
Thang Vu
06e891c0ea chore: cache output for @auth/sveltekit 2023-01-24 15:22:42 +07:00
GitHub Actions
b9a84350b5 chore(release): bump package version(s) [skip ci] 2023-01-24 02:02:00 +00:00
Balázs Orbán
44c38247da chore: trigger CI 2023-01-24 02:58:49 +01:00
Balázs Orbán
9b9af4d5e5 chore: bump versions [skip ci] 2023-01-24 02:56:31 +01:00
Balázs Orbán
fd2179bdca Merge branch 'main' of github.com:nextauthjs/next-auth 2023-01-24 02:42:16 +01:00
Balázs Orbán
7bb037bb9d chore: temp. disable E2E tests 2023-01-24 02:42:13 +01:00
Robin Panta
52f70e9f4f docs: update "guide deep-dive" link (#6473)
Fixes https://github.com/nextauthjs/next-auth/issues/6466
2023-01-24 02:34:45 +01:00
Balázs Orbán
505f69b519 chore: fix pipeline 2023-01-24 02:29:10 +01:00
Balázs Orbán
b21709db40 chore: update lock file 2023-01-24 02:26:49 +01:00
Balázs Orbán
aff7b37ef9 Merge branch 'main' of github.com:nextauthjs/next-auth 2023-01-24 02:26:00 +01:00
Balázs Orbán
daa85be1ad Revert "chore(next-auth): remove engines restriction (#6428)"
This reverts commit 035836da98.
2023-01-24 02:25:45 +01:00
Balázs Orbán
c31718ca10 fix(core): sign cookies with built-in jwt methods (#6488) 2023-01-24 02:21:56 +01:00
Balázs Orbán
fbcfedf0e8 fix(providers): default image to null for Azure AD 2023-01-24 02:21:27 +01:00
Balázs Orbán
bd032335eb docs: rename file 2023-01-23 13:41:21 +01:00
Balázs Orbán
128e0f3a10 docs: update RBAC guide 2023-01-23 13:40:45 +01:00
Thang Vu
557fb9d741 chore: ignore e2e actions in forks 2023-01-23 12:28:48 +07:00
Thang Vu
b4d6ed5f5f feat(providers): add Asgardeo provider (#6452)
* implement asgardeo auth provider

* Import asgardeo provider in to providers

* Improve provider configuration

* simplify and improve the asgardeo provider

* Delete package-lock.json

* converted server origin to organization

* revamp provider configs

* update profile interface

* Remove asgardeo issuer parameter and add docs

* fixed docs

* Update asgardeo.md

* Update docs and provider branding

* Remove mistakenly added code from dev app

* move to core

* Delete asgardeo.md

Co-authored-by: Yathindra <yathindrarawya123@gmail.com>
Co-authored-by: Yathindra Kodithuwakku <32919513+yathindrakodithuwakku@users.noreply.github.com>
Co-authored-by: Yathindra Kodithuwakku <32919513+yathindrak@users.noreply.github.com>
2023-01-22 01:30:42 +07:00
Richard Shin
035836da98 chore(next-auth): remove engines restriction (#6428)
* fix: add node 19 as compatible engine

* remove engines restriction

Co-authored-by: Thang Vu <hi@thvu.dev>
2023-01-21 16:29:45 +07:00
Atila Fassina
294039a497 docs(xata-adapter): adjust json schema (#6440) 2023-01-20 11:17:00 +00:00
Balázs Orbán
b2450ef625 fix(providers): conform Twitch provider to spec with escape hatch (#6365)
* fix(core): add explicit non-conform escape hatch

* fix(core): default to first supported auth method

* fix(core): stringify `claims` authorization url param

* fix(providers): conform Twitch provider to spec with escape hatch

* configure `client_secret_post` explicitly in provider
2023-01-19 10:28:14 +00:00
Balázs Orbán
a81bb3e51e feat(core): option to opt out of CSRF checks (#6379)
* feat(core): add way to opt-out of CSRF checks

* fix logic

* add warning if CSRF endpoint used when skipped
2023-01-19 10:27:18 +00:00
Robin Panta
bb506f7eb9 docs: Fix token expiry comparision in database strategy (#6430)
* Fix token expiry comparision in database strategy

fixes the condition used for example
in database strategy

* Apply suggestions from code review

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-18 15:26:23 +00:00
Thang Vu
87d9cc4244 feat: e2e tests (#6380)
* feat: e2e test init

* run e2e test on CI

* Add credentials to ci

* Update pnpm-lock.yaml

* move test to dev

* add dotenv

* remove in examples

* add e2e command

* revert

* add output cache for turbo e2e

* correct path for upload artifact

* Update release.yml
2023-01-18 19:43:50 +07:00
uatemycookie22
d2e3b76031 docs: Update 02-oauth-tutorial.mdx (#6408)
Fix typos in 02-oath-tutorial.mdx
2023-01-17 00:24:48 +01:00
Jan-David-Black
c36834b3b0 docs: Updating to _app.tsx (#6398)
file should be called `_app.tsx` instead of `_app.ts`
2023-01-17 00:24:04 +01:00
khuezy
8f7145801a feat(adapters): expose DynamoDB adapter options (#6370)
* feat: add dynmodb adaption options

* fix typo

* Apply suggestions from code review

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-12 09:59:18 +00:00
Balázs Orbán
fdce27b8ca fix(providers): remove Twitter OAuth 2.0 workaround 2023-01-11 13:00:15 +01:00
Rhys
4056dafa7a docs: Minor grammar in email docs (#6358)
Grammar in email docs
2023-01-11 07:56:08 +01:00
Mahammedi Abdelghani
f0b61bd5fd docs: fix broken links (#6359)
- fix some Provider options links ".js" --> ".ts"
2023-01-11 07:55:27 +01:00
Thang Vu
866e42b343 chore: revert to latest dependencies for examples 2023-01-10 21:05:06 +07:00
${Mr.DJA}
6d4cde4b02 feat(core): allow clearing cookies from jwt() (#6337)
* feat(core): allow clearing cookies from `jwt()`

* revert: allow clearing cookies from `jwt()`

* feat(core): re-apply changes against `@auth/core`

* revert: `decodeJWT` option

* doc: `jwt()` callback

* Apply suggestions from code review

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-10 12:11:52 +00:00
Ben
2377596bb6 chore(examples): avoid prefetch of non-existing routes in SvelteKit (#6351)
Avoid prefetch of non-existing routes

This avoids prefetch of the /auth/signin and /auth/signout virtual links as they do not exist in sveltkit routes
2023-01-10 11:56:25 +00:00
Balázs Orbán
3c7c25cefa docs: improve some provider docs 2023-01-10 12:51:39 +01:00
Thang Vu
c441f681af chore: don't use latest for examples dependencies 2023-01-10 13:37:51 +07:00
Balázs Orbán
c05951f0f9 docs: add Auth0 and GitHub header 2023-01-09 16:53:30 +01:00
Balázs Orbán
d142252499 chore: update lock file, prettier config 2023-01-09 13:29:28 +01:00
Nathan Meadows
700daec919 fix(docs): page.server.ts -> layout.server.ts (#6326)
Fix documentation mistake - page.server.ts -> layout.server.ts
2023-01-09 08:43:34 +00:00
OrJDev
d8481f3825 chore(core): use arrow function for generateSessionToken (#6200)
* fix

* prettify

* Update init.ts

Co-authored-by: Nico Domino <yo@ndo.dev>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-09 08:38:33 +00:00
Balázs Orbán
3539a35601 chore: trigger sync 2023-01-07 09:52:33 +01:00
Balázs Orbán
3be7bb7a79 chore: try fork 2023-01-07 09:50:12 +01:00
Balázs Orbán
031cdd13b2 chore: try adding deleteOrphaned back 2023-01-07 09:37:00 +01:00
Balázs Orbán
212b321f7e chore: remove delete orphaned 2023-01-07 09:29:23 +01:00
Balázs Orbán
1ccb88b3f0 chore: try excluding git 2023-01-07 09:27:35 +01:00
Balázs Orbán
16d680b110 chore: revert 2023-01-07 09:04:13 +01:00
Balázs Orbán
6e027811ef chore: set git config globally 2023-01-07 09:01:33 +01:00
Balázs Orbán
e5df406429 chore: try adding email+username 2023-01-07 08:56:25 +01:00
Balázs Orbán
e4ddb533ff chore: hint that we want to use fine grained GH_PAT 2023-01-07 08:48:15 +01:00
Balázs Orbán
4e16b21a60 chore: update sync GH Action 2023-01-07 08:41:43 +01:00
Balázs Orbán
dd9f1b7421 chore: move provider logos under /img 2023-01-07 08:12:24 +01:00
Balázs Orbán
4ebec5d385 docs: fix marquee 2023-01-07 08:04:56 +01:00
Balázs Orbán
c1f3cbda3c chore: move icons to website 2023-01-07 08:02:27 +01:00
Sacramentix
ba3ed049d1 fix: typo on example resposne -> response (#6311) 2023-01-07 07:49:56 +01:00
Balázs Orbán
9238294192 feat(core): Redesigned all default pages (#5825)
* feat(pages): Redesigned all default pages according to sketches discussed.

* chore(signin): Remove console.log

* fix(css): Makes cards scale down to 320px and have a fixed width on larger screens

* fix(styling): Adds margins on bottom and top of card.

* chore(docs): Change the documentation according to changes. Uploaded new images that reflect the new pages.

* fix(next-auth/core): Fixes correct styling of provider button across browsers.

* chore(docs): Add doc string to beta docs aswell

* feat: move changes to core

* revert change in next-auth

Co-authored-by: Nico Domino <yo@ndo.dev>
Co-authored-by: Thang Vu <hi@thvu.dev>
revert signin
2023-01-07 07:49:56 +01:00
Balázs Orbán
83c6bfe237 fix(core): improve stack traces (#6259) 2023-01-07 07:47:30 +01:00
Tyler Miller
07109616c8 docs(sveltekit): Typo fix (#6309)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2023-01-07 07:47:30 +01:00
Ikko Eltociear Ashimine
95c8f7930e chore: Fix typo in solid-start/README.MD (#6305) 2023-01-07 07:47:30 +01:00
Thang Vu
8005f0cdb0 chore: update watch command for next-auth dev 2023-01-07 07:47:30 +01:00
Finn
6e0ae59ed3 docs(providers): added JS doc's to the mattermost provider (#6299)
* aded js doc

* engerish
2023-01-07 07:47:30 +01:00
Kostas Botsas
1b19aa39b8 fix(adapters): remove formatVersion from Xata schema (#5772)
Xata schema has removed the formatVersion field, including it in a schema definition results in an error.
2023-01-07 07:47:30 +01:00
Balázs Orbán
69cda58707 fix(core): move types submodule top top 2023-01-07 07:47:30 +01:00
Balázs Orbán
b20a5f554a feat(providers): add Mattermost provider (#6290)
* added mattermost provider

* upaded docs and removed callback uri

* username -> name

* updated types to match other providers

* cleanup

* add logos

* style sign-in button

* add JSDoc to profile

* add JSDoc comments

* correction

Co-authored-by: Balázs Orbán <info@balazsorban.com>
delete mattermost icons
2023-01-07 07:47:30 +01:00
Balázs Orbán
f8d77c4daf chore: hardcode issue labeler markdown path 2023-01-05 12:14:57 +01:00
Balázs Orbán
a3d23450a8 chore: fix issue labeler path 2023-01-05 12:09:44 +01:00
Balázs Orbán
9abee0b2ee chore: use import.meta.url in issue labeler 2023-01-05 12:07:44 +01:00
Balázs Orbán
5cf580d10b chore(examples): clean up example READMEs, add deploy buttons 2023-01-05 11:18:01 +01:00
Thang Vu
00d495d9e3 chore: update email script 2023-01-04 21:54:22 +07:00
Thang Vu
5884574765 chore(dev): simplify header.js component 2023-01-04 21:53:55 +07:00
Thang Vu
ae5360b028 chore: cache output for @auth/core 2023-01-04 21:52:42 +07:00
Doodles
7c963515b5 docs: Add session management example for SvelteKit (#6184)
* chore(docs): Session management sample for Svelte

Added a code sample for managing the session through the $page store.
The sample demonstrates how to retrieve the session data in the root
+page.server.ts file and make it globally accessible through the $page
store, simplifying state management in the application. The previous
examples already used the data available in this store but did not show
how to set it.

* docs: Add authorization section to SvelteKit docs

This authorization section was added to make sure a few caveats with
SvelteKit were well documented to anyone using the library.

The problem is documented here: https://github.com/sveltejs/kit/issues/6315

Essentially, propagation of data between leafs is not guaranteed when
using the +layout.server.ts file as its load function is not guaranteed
to rerun every page change. The current approach to solve this is to do
authorization in each +page.server.ts file and additionally make sure to
grab the session data by awaiting the parent instead of directly
accessing the $page store, to make sure the information there is
current.

* docs: Fix small typesafety mistake in SvelteKit

PageLoad type should actually be PageServerLoad. Not setting this does
not actually generate any problems other than TypeScript complaining
that this type is not actually exported.

* docs: Add handle hook authorization management

Another way to handle authorization is through a path-based method. This
added part of the documentation uses the handle hook to protect certain
routes based on their path. The previous method which is per-component
is still present.

* docs: Simplify component approach for Svelte auth

Using event.locals.getSession() exposed by SvelteKitAuth instead of
relying in the root layout file making that available in the $page
store.

* docs: Complete SvelteKit authorization docs

Finalize the explanation for the URI-based approach and also clarify
interactions with the component-based approach.

* docs: Add formatting to vars in the SvelteKit docs

Format the variables like this: `var` so that it appears clearly as code
when reading the documentation.

Co-authored-by: Thang Vu <hi@thvu.dev>
2023-01-04 21:49:18 +07:00
Robin Gasi
8cf4cc2ea9 docs: Fixed typo (#6277) 2023-01-04 08:58:57 +00:00
GitHub Actions
9388a56efa chore(release): bump package version(s) [skip ci] 2023-01-04 06:56:11 +00:00
Balázs Orbán
3a75fb955a docs: simplify refresh token guide 2023-01-04 07:49:11 +01:00
Balázs Orbán
01bb91612a fix(core): allow passing params only to endpoint configs
fixes #6273
2023-01-04 07:48:57 +01:00
Balázs Orbán
3b25935c83 fix(core): correctly pass user id in account
fixes #6209, fixes #6222
2023-01-03 16:26:49 +01:00
Balázs Orbán
394920dfd4 chore(examples): prefer useSession over prop drilling
closes #5891
2023-01-03 16:07:37 +01:00
Raouf Chebri
85dc5bede8 docs: Update strava provider option url (#6264)
Update strava.md
2023-01-03 15:55:36 +01:00
Balázs Orbán
8f854c61d0 fix(core): allow custom endpoint config when issuer is present
closes #6244
2023-01-03 12:11:13 +01:00
Balázs Orbán
e8fbe58997 docs: update refresh token guide 2023-01-03 12:09:13 +01:00
Cameron Downey
d2288ee4cc fix(docs): turn SvelteKitAuth to named import in code example (#6250) 2023-01-02 10:52:47 +00:00
Thang Vu
5a6f76bf2c fix: docs build (#6253)
* fix: docs build

* chore: move next-auth output to dist

* chore: add next-auth as deps for doc

* Revert "chore: move next-auth output to dist"

This reverts commit 9596a9134e6de4f4bd8dcfaa6d3002e98863d8f8.

* remove dist prefix
2023-01-02 16:57:14 +07:00
Thang Vu
15bed6260c chore: change Thang's email 2023-01-01 22:45:36 +07:00
Balázs Orbán
1423733d61 fix(adapters): define correct peer dependencies for DynamoDB (#6249)
* Add @aws-sdk/client-dynamodb as peer dependency

* Add missing DynamoDBClientConfig interface import

* Add missing installation requirements

Co-authored-by: Didi Keke <nyedidikeke@users.noreply.github.com>
2023-01-01 15:16:01 +00:00
Thang Vu
77d8f47f51 chore: restore turborepo next-auth#build.outputs 2023-01-01 22:06:50 +07:00
Balázs Orbán
3120d28299 chore: update lockfile 2023-01-01 16:03:09 +01:00
Nico Domino
e6a320bb0f chore(docs): fix homepage logo, build, and lighthouse improvements (#6238)
* chore(docs): fix homepage logo size

* chore(docs): fix sidebars.js solid-start doc path name

* chore(docs): image file and size optimizations

* chore(docs): fix semantic misordered headings

* chore(docs): make banner link more descriptive

* chore(docs): add solid-start redirect
2022-12-31 21:28:59 +01:00
Birk Skyum
7d4d436efe chore(examples): fix broken docs link in solidstart example (#6241) 2022-12-31 21:28:17 +01:00
GitHub Actions
c6f5c4d1cf chore(release): bump package version(s) [skip ci] 2022-12-31 11:09:43 +00:00
Balázs Orbán
09a075cc7e fix(core): loosen dependency version requirements 2022-12-31 12:05:23 +01:00
Balázs Orbán
f1475955ea chore: solidstart -> solid-start 2022-12-31 11:53:29 +01:00
Balázs Orbán
e6f48775fa chore: add packages to docs build dependency list 2022-12-31 11:44:40 +01:00
Balázs Orbán
ba87e86d47 chore: update lock file 2022-12-31 11:42:08 +01:00
Balázs Orbán
b0dd1fac93 chore: disable solid start example sync (temp) 2022-12-31 11:34:49 +01:00
Balázs Orbán
054288316b chore(examples): rename solid-start to solidstart 2022-12-31 11:31:47 +01:00
Balázs Orbán
5e02019a3c chore: what is yaml 2022-12-31 10:23:17 +00:00
Balázs Orbán
9da0e66193 chore: fix indent 2022-12-31 10:20:48 +00:00
OrJDev
287c8f0f91 feat(solid-start): introduce @auth/solid-start package/example (#6158)
* feat: add solid framework package and example

* solidstart docs

* Update 02-oauth-tutorial.mdx

* minor docs fixes

* Fix sidebar typo

* Update sync.yml

* Update sidebars.js

* minor fixes

* fix deps

* upgrade auth example

* Update root.tsx

* Update NavBar.tsx

* Update Protected.tsx

* protected

* move example

* Update sidebars.js

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Nico Domino <yo@ndo.dev>
2022-12-31 10:15:31 +00:00
Balázs Orbán
87ed5077ad fix(sveltekit): make AUTH_SECRET dynamic
fixes #6231
2022-12-31 10:45:42 +01:00
Jonny
2cbf815445 fix(ts): add function overload to getToken (#5823)
* added function overload to getToken

* use MissingSecret error instead

* had wrong import

* change in core

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2022-12-31 09:26:23 +00:00
박찬혁
d63166db3a fix(ts): narrow Kakao's birtday_type profile property type (#6036)
* feat: type safety for BirthDay

* update in core

* birthday single word

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2022-12-31 08:32:26 +00:00
Håkon Collett Bjørgan
f387793d71 fix(core): clarify that JWT is encrypted by default (#5824)
* fix(core): update CallbacksOptions.jwt docstring

Change description to reflect that JWT is encrypted by default

* update in core

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2022-12-31 07:52:48 +00:00
453 changed files with 14145 additions and 16122 deletions

View File

@@ -1,70 +0,0 @@
.eslintrc.js
.cache-loader
.DS_Store
.pnpm-debug.log
.turbo
.vscode/generated*
/_work
/actions-runner
node_modules
patches
pnpm-lock.yaml
.github/actions/issue-validator/index.mjs
*.cjs
*.js
*.d.ts
*.d.ts.map
.svelte-kit
.next
.nuxt
# --------------- Docs ---------------
.docusaurus
build
docs/docs/reference/03-core
docs/docs/reference/04-sveltekit
static
# --------------- Packages ---------------
coverage
dist
# @auth/core
packages/core/src/providers/oauth-types.ts
packages/core/src/lib/pages/styles.ts
# @auth/sveltekit
packages/frameworks-sveltekit/package
packages/frameworks-sveltekit/vite.config.{js,ts}.timestamp-*
# next-auth
packages/next-auth/src/providers/oauth-types.ts
packages/next-auth/css/index.css
# Adapters
.branches
db.sqlite
dev.db
dynamodblocal-bin
firebase-debug.log
firestore-debug.log
migrations
test.schema.gql
# --------------- Apps ---------------
# Examples should have their own Prettier config since they are templates too
apps/example-sveltekit
# Development app
apps
# --------------- Tests ---------------
# TODO: these should be linted
packages/**/*test*

View File

@@ -1,75 +0,0 @@
// @ts-check
/** @type {import("eslint").ESLint.ConfigData} */
module.exports = {
env: { browser: true, es2022: true, node: true },
extends: ["eslint:recommended", "prettier"],
overrides: [
{
files: ["*.ts", "*.tsx"],
parser: "@typescript-eslint/parser",
parserOptions: {
project: ["./packages/**/tsconfig.json", "./apps/**/tsconfig.json"],
},
settings: { react: { version: "18" } },
extends: [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"standard-with-typescript",
"prettier",
],
rules: {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/method-signature-style": "off",
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/strict-boolean-expressions": "off",
"react/prop-types": "off",
"react/no-unescaped-entities": "off",
},
},
{
files: ["*.test.ts", "*.test.js"],
extends: ["plugin:jest/recommended"],
env: { jest: true },
},
{
files: ["docs/**"],
plugins: ["@docusaurus"],
extends: ["plugin:@docusaurus/recommended"],
},
{
// TODO: Expand to all packages
files: ["packages/{core,sveltekit}/*.ts"],
plugins: ["jsdoc"],
extends: ["plugin:jsdoc/recommended"],
rules: {
"jsdoc/require-param": "off",
"jsdoc/require-returns": "off",
"jsdoc/require-jsdoc": [
"warn",
{ publicOnly: true, enableFixer: false },
],
"jsdoc/no-multi-asterisks": ["warn", { allowWhitespace: true }],
"jsdoc/tag-lines": "off",
},
},
{
files: ["packages/frameworks-sveltekit"],
plugins: ["svelte3"],
overrides: [{ files: ["*.svelte"], processor: "svelte3/svelte3" }],
settings: {
"svelte3/typescript": () => require("typescript"),
},
parserOptions: { sourceType: "module", ecmaVersion: 2020 },
env: { browser: true, es2017: true, node: true },
},
],
parserOptions: {
sourceType: "module",
ecmaVersion: "latest",
ecmaFeatures: { jsx: true },
},
root: true,
}

View File

@@ -30,7 +30,7 @@ body:
Run this command in your project's root folder and paste the result:
```sh
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth"
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth,@auth/*"
```
Alternatively, you can manually gather the version information from your package.json for these packages: "next", "react" and "next-auth". Please also mention your OS and Node.js version, as well as the browser you are using.
validations:

View File

@@ -25,12 +25,14 @@ body:
- "Custom provider"
- "42 School"
- "Apple"
- "Asgardeo"
- "Atlassian"
- "Auth0"
- "Authentik"
- "Azure Active Directory"
- "Azure Active Directory B2C"
- "Battlenet"
- "Beyond Identity"
- "Box"
- "Bungie"
- "Cognito"
@@ -57,6 +59,7 @@ body:
- "Medium"
- "Naver"
- "Netlify"
- "Notion"
- "Okta"
- "OneLogin"
- "Osso"
@@ -87,7 +90,7 @@ body:
Run this command in your project's root folder and paste the result:
```sh
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth"
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth,@auth/*"
```
Alternatively, you can manually gather the version information from your package.json for these packages: "next", "react" and "next-auth". Please also mention your OS and Node.js version, as well as the browser you are using.
validations:

View File

@@ -44,7 +44,7 @@ body:
Run this command in your project's root folder and paste the result:
```sh
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth" && npx envinfo --npmPackages "@next-auth/*"
npx envinfo --system --binaries --browsers --npmPackages "next,react,next-auth,@auth/*" && npx envinfo --npmPackages "@next-auth/*"
```
Alternatively, if the above command did not work, we need the version of the following packages from your package.json: "next", "react", "next-auth" and your adapter. Please also mention your OS and Node.js version, as well as the browser you are using.
validations:

File diff suppressed because one or more lines are too long

View File

@@ -14,9 +14,9 @@ Ensure the link is pointing to a codebase that is accessible (e.g. not a private
### **What happens if I don't provide a sufficient minimal reproduction?**
Issues with the `incomplete` label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.
Issues with the `incomplete` label that receives no meaningful activity (e.g. new comments with a reproduction link) are closed after 7 days.
If your issue has _not_ been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.
If your issue has _not_ been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction. (It's less likely that we check back on already closed issues.)
### **I did not open this issue, but it is relevant to me, what can I do to help?**

View File

@@ -41,13 +41,7 @@ async function run() {
label: { name: newLabel },
} = payload
if (
pull_request ||
!issue?.body ||
!process.env.GITHUB_TOKEN ||
!process.env.GITHUB_ACTION_PATH
)
return
if (pull_request || !issue?.body || !process.env.GITHUB_TOKEN) return
const labels = issue.labels.map((l) => l.name)
// const isBugReport =
@@ -78,7 +72,9 @@ async function run() {
client.issues.createComment({
...issueCommon,
body: readFileSync(
join(process.env.GITHUB_ACTION_PATH, "repro.md"),
join(
"/home/runner/work/next-auth/next-auth/.github/actions/issue-validator/repro.md"
),
"utf8"
),
}),

7
.github/sync.yml vendored
View File

@@ -7,6 +7,13 @@ nextauthjs/sveltekit-auth-example:
- .github/FUNDING.yml
- LICENSE
nextauthjs/solid-start-auth-example:
- source: "apps/examples/solid-start"
dest: .
deleteOrphaned: true
- .github/FUNDING.yml
- LICENSE
nextauthjs/next-auth-gatsby-example:
- source: apps/playgrounds/gatsby
dest: .

View File

@@ -11,7 +11,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: 18
- name: "Run issue validator"
- name: Run issue validator
run: node /home/runner/work/next-auth/next-auth/.github/actions/issue-validator/index.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -3,10 +3,10 @@ name: Release
on:
push:
branches:
- "main"
- "beta"
- "next"
- "3.x"
- main
- beta
- next
- 3.x
pull_request:
jobs:
@@ -24,7 +24,6 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Run tests
@@ -35,6 +34,22 @@ jobs:
UPSTASH_REDIS_KEY: ${{ secrets.UPSTASH_REDIS_KEY }}
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
# - name: Run E2E tests
# if: github.repository == 'nextauthjs/next-auth'
# run: pnpm e2e
# timeout-minutes: 15
# env:
# AUTH0_USERNAME: ${{ secrets.AUTH0_USERNAME }}
# AUTH0_PASSWORD: ${{ secrets.AUTH0_PASSWORD }}
# TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
# TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
# - name: Upload E2E artifacts
# if: github.repository == 'nextauthjs/next-auth'
# uses: actions/upload-artifact@v3
# with:
# name: playwright-report
# path: apps/dev/nextjs/playwright-report/
# retention-days: 30
# - name: Coverage
# uses: codecov/codecov-action@v1
# with:
@@ -58,7 +73,6 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Publish to npm and GitHub
@@ -83,7 +97,6 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Determine version

View File

@@ -11,9 +11,9 @@ jobs:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Run GitHub File Sync
# Can update to v1 when https://github.com/BetaHuhn/repo-file-sync-action/issues/168 is resolved
uses: BetaHuhn/repo-file-sync-action@v1.16.5
uses: balazsorban44/repo-file-sync-action@master
with:
GH_PAT: ${{ secrets.GH_PAT_CLASSIC }}
GH_PAT: ${{ secrets.GH_PAT }}
IS_FINE_GRAINED: true
SKIP_PR: true
ORIGINAL_MESSAGE: true

25
.gitignore vendored
View File

@@ -1,6 +1,5 @@
# Misc
.DS_Store
.npmrc
.eslintcache
.env
.env.local
@@ -12,8 +11,9 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log
ui-debug.log
.pnpm-debug.log
.husky
# Dependencies
node_modules
@@ -34,13 +34,10 @@ packages/next-auth/utils
packages/next-auth/core
packages/next-auth/jwt
packages/next-auth/react
packages/next-auth/adapters.d.ts
packages/next-auth/adapters.js
packages/next-auth/index.d.ts
packages/next-auth/index.js
packages/next-auth/next
packages/next-auth/middleware.d.ts
packages/next-auth/middleware.js
packages/*/*.js
packages/*/*.d.ts
packages/*/*.d.ts.map
# Development app
apps/dev/src/css
@@ -81,14 +78,12 @@ docs/.docusaurus
docs/providers.json
# Core
packages/core/*.js
packages/core/*.d.ts
packages/core/*.d.ts.map
packages/core/src/providers/oauth-types.ts
packages/core/lib
packages/core/providers
packages/core/src/lib/pages/styles.ts
docs/docs/reference/03-core
docs/docs/reference/04-sveltekit
docs/docs/reference/core
docs/docs/reference/sveltekit
# SvelteKit
@@ -98,3 +93,7 @@ packages/frameworks-sveltekit/.svelte-kit
packages/frameworks-sveltekit/package
packages/frameworks-sveltekit/vite.config.js.timestamp-*
packages/frameworks-sveltekit/vite.config.ts.timestamp-*
# Adapters
docs/docs/reference/adapter

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
public-hoist-pattern[]=*prisma*

View File

@@ -20,8 +20,8 @@ pnpm-lock.yaml
.docusaurus
build
docs/docs/reference/03-core
docs/docs/reference/04-sveltekit
docs/docs/reference/core
docs/docs/reference/sveltekit
static
docs/providers.json

View File

@@ -1,22 +0,0 @@
// @ts-check
/** @type {import("prettier").Config} */
module.exports = {
semi: false,
singleQuote: false,
overrides: [
{
files: [
"apps/dev/pages/api/auth/[...nextauth].ts",
"docs/{sidebars,docusaurus.config}.js",
],
options: { printWidth: 150 },
},
{
files: ["**/*package.json"],
options: {
trailingComma: "none",
},
},
],
}

View File

@@ -9,20 +9,39 @@ NEXTAUTH_URL=http://localhost:3000
# and/or verification tokens.
NEXTAUTH_SECRET=secret
ASGARDEO_CLIENT_ID=
ASGARDEO_CLIENT_SECRET=
ASGARDEO_ISSUER=
AUTH0_ID=
AUTH0_SECRET=
AUTH0_ISSUER=
KEYCLOAK_ID=
KEYCLOAK_SECRET=
KEYCLOAK_ISSUER=
# Beyond Identity Provider
BEYOND_IDENTITY_CLIENT_ID=
BEYOND_IDENTITY_CLIENT_SECRET=
BEYOND_IDENTITY_ISSUER=
GITHUB_ID=
GITHUB_SECRET=
NOTION_ID=
NOTION_SECRET=
NOTION_REDIRECT_URI=
IDS4_ID=
IDS4_SECRET=
IDS4_ISSUER=
GITHUB_ID=
GITHUB_SECRET=
KEYCLOAK_ID=
KEYCLOAK_SECRET=
KEYCLOAK_ISSUER=
LINE_ID=
LINE_SECRET=
TRAKT_ID=
TRAKT_SECRET=
TWITCH_ID=
TWITCH_SECRET=
@@ -30,11 +49,12 @@ TWITCH_SECRET=
TWITTER_ID=
TWITTER_SECRET=
LINE_ID=
LINE_SECRET=
WIKIMEDIA_ID=
WIKIMEDIA_SECRET=
TRAKT_ID=
TRAKT_SECRET=
# Yandex OAuth. new app -> https://oauth.yandex.com/client/new/id
YANDEX_ID=
YANDEX_SECRET=
# Example configuration for a Gmail account (will need SMTP enabled)
EMAIL_SERVER=smtps://user@gmail.com:password@smtp.gmail.com:465
@@ -47,12 +67,9 @@ EMAIL_FROM=user@gmail.com
# MongoDB: DATABASE_URL=mongodb://nextauth:password@127.0.0.1:27017/nextauth?synchronize=true
DATABASE_URL=
WIKIMEDIA_ID=
WIKIMEDIA_SECRET=
# Supabase Example Configuration
# Supabase Example Configuration
# NEXT_PUBLIC_SUPABASE_URL=http://localhost:54321
# SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSJ9.vI9obAHOGyVVKa3pD--kJlyxp-Z2zV9UUMAhKpNLAcU
# SUPABASE_JWT_SECRET=super-secret-jwt-token-with-at-least-32-characters-long
# NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs
# NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs

4
apps/dev/nextjs/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
/test-results/
/playwright-report/
/playwright/.cache/

View File

@@ -1,5 +1,5 @@
import Link from "next/link"
import { signIn, signOut, useSession } from "next-auth/react"
import { useSession } from "next-auth/react"
import styles from "./header.module.css"
// The approach used in this component shows how to built a sign in and sign out
@@ -24,14 +24,7 @@ export default function Header() {
<span className={styles.notSignedInText}>
You are not signed in
</span>
<a
href="/api/auth/signin"
className={styles.buttonPrimary}
onClick={(e) => {
e.preventDefault()
signIn()
}}
>
<a href="/api/auth/signin" className={styles.buttonPrimary}>
Sign in
</a>
</>
@@ -47,14 +40,7 @@ export default function Header() {
<strong>{session.user.email} </strong>
{session.user.name ? `(${session.user.name})` : null}
</span>
<a
href="/api/auth/signout"
className={styles.button}
onClick={(e) => {
e.preventDefault()
signOut()
}}
>
<a href="/api/auth/signout" className={styles.button}>
Sign out
</a>
</>

View File

@@ -9,10 +9,12 @@
"build": "next build",
"start": "next start",
"email": "fake-smtp-server",
"start:email": "pnpm email"
"start:email": "pnpm email",
"e2e": "pnpm dlx playwright test"
},
"license": "ISC",
"dependencies": {
"@auth/core": "workspace:*",
"@next-auth/fauna-adapter": "workspace:*",
"@next-auth/prisma-adapter": "workspace:*",
"@next-auth/supabase-adapter": "workspace:*",
@@ -22,15 +24,16 @@
"faunadb": "^4",
"next": "13.1.1",
"next-auth": "workspace:*",
"@auth/core": "workspace:*",
"nodemailer": "^6",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@playwright/test": "1.29.2",
"@types/jsonwebtoken": "^8.5.5",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"dotenv": "^16.0.3",
"fake-smtp-server": "^0.8.0",
"pg": "^8.7.3",
"prisma": "^3",

View File

@@ -2,9 +2,11 @@ import { Auth, type AuthConfig } from "@auth/core"
// Providers
import Apple from "@auth/core/providers/apple"
import Asgardeo from "@auth/core/providers/asgardeo"
import Auth0 from "@auth/core/providers/auth0"
import AzureAD from "@auth/core/providers/azure-ad"
import AzureB2C from "@auth/core/providers/azure-ad-b2c"
import BeyondIdentity from "@auth/core/providers/beyondidentity"
import BoxyHQSAML from "@auth/core/providers/boxyhq-saml"
// import Cognito from "@auth/core/providers/cognito"
import Credentials from "@auth/core/providers/credentials"
@@ -23,6 +25,7 @@ import Instagram from "@auth/core/providers/instagram"
import Line from "@auth/core/providers/line"
import LinkedIn from "@auth/core/providers/linkedin"
import Mailchimp from "@auth/core/providers/mailchimp"
import Notion from "@auth/core/providers/notion"
// import Okta from "@auth/core/providers/okta"
import Osu from "@auth/core/providers/osu"
import Patreon from "@auth/core/providers/patreon"
@@ -31,6 +34,7 @@ import Spotify from "@auth/core/providers/spotify"
import Trakt from "@auth/core/providers/trakt"
import Twitch from "@auth/core/providers/twitch"
import Twitter from "@auth/core/providers/twitter"
import Yandex from "@auth/core/providers/yandex"
import Vk from "@auth/core/providers/vk"
import Wikimedia from "@auth/core/providers/wikimedia"
import WorkOS from "@auth/core/providers/workos"
@@ -68,7 +72,7 @@ import WorkOS from "@auth/core/providers/workos"
export const authConfig: AuthConfig = {
// adapter,
// debug: process.env.NODE_ENV !== "production",
debug: process.env.NODE_ENV !== "production",
theme: {
logo: "https://next-auth.js.org/img/logo/logo-sm.png",
brandColor: "#1786fb",
@@ -82,6 +86,7 @@ export const authConfig: AuthConfig = {
},
}),
Apple({ clientId: process.env.APPLE_ID, clientSecret: process.env.APPLE_SECRET }),
Asgardeo({ clientId: process.env.ASGARDEO_CLIENT_ID, clientSecret: process.env.ASGARDEO_CLIENT_SECRET, issuer: process.env.ASGARDEO_ISSUER }),
Auth0({ clientId: process.env.AUTH0_ID, clientSecret: process.env.AUTH0_SECRET, issuer: process.env.AUTH0_ISSUER }),
AzureAD({
clientId: process.env.AZURE_AD_CLIENT_ID,
@@ -89,6 +94,7 @@ export const authConfig: AuthConfig = {
tenantId: process.env.AZURE_AD_TENANT_ID,
}),
AzureB2C({ clientId: process.env.AZURE_B2C_ID, clientSecret: process.env.AZURE_B2C_SECRET, issuer: process.env.AZURE_B2C_ISSUER }),
BeyondIdentity({ clientId: process.env.BEYOND_IDENTITY_CLIENT_ID, clientSecret: process.env.BEYOND_IDENTITY_CLIENT_SECRET, issuer: process.env.BEYOND_IDENTITY_ISSUER }),
BoxyHQSAML({ issuer: "https://jackson-demo.boxyhq.com", clientId: "tenant=boxyhq.com&product=saml-demo.boxyhq.com", clientSecret: "dummy" }),
// Cognito({ clientId: process.env.COGNITO_ID, clientSecret: process.env.COGNITO_SECRET, issuer: process.env.COGNITO_ISSUER }),
Discord({ clientId: process.env.DISCORD_ID, clientSecret: process.env.DISCORD_SECRET }),
@@ -105,6 +111,7 @@ export const authConfig: AuthConfig = {
Line({ clientId: process.env.LINE_ID, clientSecret: process.env.LINE_SECRET }),
LinkedIn({ clientId: process.env.LINKEDIN_ID, clientSecret: process.env.LINKEDIN_SECRET }),
Mailchimp({ clientId: process.env.MAILCHIMP_ID, clientSecret: process.env.MAILCHIMP_SECRET }),
Notion({ clientId: process.env.NOTION_ID, clientSecret: process.env.NOTION_SECRET, redirectUri: process.env.NOTION_REDIRECT_URI }),
// Okta({ clientId: process.env.OKTA_ID, clientSecret: process.env.OKTA_SECRET, issuer: process.env.OKTA_ISSUER }),
Osu({ clientId: process.env.OSU_CLIENT_ID, clientSecret: process.env.OSU_CLIENT_SECRET }),
Patreon({ clientId: process.env.PATREON_ID, clientSecret: process.env.PATREON_SECRET }),
@@ -114,6 +121,7 @@ export const authConfig: AuthConfig = {
Twitch({ clientId: process.env.TWITCH_ID, clientSecret: process.env.TWITCH_SECRET }),
Twitter({ clientId: process.env.TWITTER_ID, clientSecret: process.env.TWITTER_SECRET }),
// TwitterLegacy({ clientId: process.env.TWITTER_LEGACY_ID, clientSecret: process.env.TWITTER_LEGACY_SECRET }),
Yandex({ clientId: process.env.YANDEX_ID, clientSecret: process.env.YANDEX_SECRET }),
Vk({ clientId: process.env.VK_ID, clientSecret: process.env.VK_SECRET }),
Wikimedia({ clientId: process.env.WIKIMEDIA_ID, clientSecret: process.env.WIKIMEDIA_SECRET }),
WorkOS({ clientId: process.env.WORKOS_ID, clientSecret: process.env.WORKOS_SECRET }),

View File

@@ -0,0 +1,107 @@
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 30 * 1000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
},
},
{
name: 'webkit',
use: {
...devices['Desktop Safari'],
},
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: {
// ...devices['Pixel 5'],
// },
// },
// {
// name: 'Mobile Safari',
// use: {
// ...devices['iPhone 12'],
// },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: {
// channel: 'msedge',
// },
// },
// {
// name: 'Google Chrome',
// use: {
// channel: 'chrome',
// },
// },
],
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
// outputDir: 'test-results/',
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// port: 3000,
// },
};
export default config;

View File

@@ -0,0 +1,39 @@
import { test, expect } from "@playwright/test"
test("Sign in with Auth0", async ({ page }) => {
// Go to NextAuth example app
await page.goto("https://next-auth-example.vercel.app")
// Click 'Sign In'
await page.click("#__next > header > div > p > a")
// Auth0 Login Provider
await page.click('body > div > div form[action*="auth0"] > button')
// Enter Credentials (Username/Password Login) on Auth0 Widget
await page.type("#username", process.env.AUTH0_USERNAME!)
await page.type("#password", process.env.AUTH0_PASSWORD!)
// Snap a screenshot
// await page.screenshot({ path: "1-auth0-login.png", fullPage: true })
// Press submit on Auth0 form
await page.click('body > div > main > section > div button[type="submit"]')
// Wait for next-auth example page login status header to appear
await page.waitForTimeout(2000)
// Snap a screenshot
// await page.screenshot({
// path: "2-next-auth-redirect-result.png",
// fullPage: false,
// })
// Check session object after successful login
const response = await page.goto(
"https://next-auth-example.vercel.app/api/auth/session"
)
const session = await response?.json()
expect(session?.user?.email).toBe(process.env.AUTH0_USERNAME)
// TODO: Check whole object with .toEqual()
})

View File

@@ -19,8 +19,8 @@
"vite": "4.0.1"
},
"dependencies": {
"@auth/core": "latest",
"@auth/sveltekit": "latest"
"@auth/core": "workspace:*",
"@auth/sveltekit": "workspace:*"
},
"type": "module"
}

View File

@@ -1,9 +1,14 @@
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/example-nextjs). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/examples/nextjs). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img width="150px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>
<h3 align="center">NextAuth.js Example App</h3>
<a href="https://authjs.dev" target="_blank">
<img height="64" src="https://authjs.dev/img/logo/logo-sm.png" />
</a>
<a href="https://nextjs.org" target="_blank">
<img height="64" src="https://nextjs.org/static/favicon/android-chrome-192x192.png" />
</a>
<h3 align="center"><b>NextAuth.js</b> - Example App</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
@@ -25,20 +30,14 @@
## Overview
NextAuth.js is a complete open source authentication solution.
NextAuth.js is a complete open-source authentication solution.
This is an example application that shows how `next-auth` is applied to a basic Next.js app.
The deployed version can be found at [`next-auth-example.vercel.app`](https://next-auth-example.vercel.app)
### About NextAuth.js
NextAuth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for [Next.js](https://nextjs.org) and [Serverless](https://vercel.com). Our goal is to [support even more frameworks](https://github.com/nextauthjs/next-auth/issues/2294) in the future.
Go to [next-auth.js.org](https://next-auth.js.org) for more information and documentation.
> _NextAuth.js is not officially associated with Vercel or Next.js._
## Getting Started
### 1. Clone the repository and install dependencies
@@ -98,15 +97,13 @@ npm run start
### 5. Preparing for Production
Follow the [Deployment documentation](https://next-auth.js.org/deployment)
Follow the [Deployment documentation](https://authjs.dev/guides/basics/deployment) or deploy the example instantly using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-auth-example)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/nextauthjs/next-auth-example&project-name=next-auth-example&repository-name=next-auth-example)
## Acknowledgements
<a href="https://vercel.com?utm_source=nextauthjs&utm_campaign=oss">
<img width="170px" src="https://raw.githubusercontent.com/nextauthjs/next-auth/canary/www/static/img/powered-by-vercel.svg" alt="Powered By Vercel" />
<img width="170px" src="https://raw.githubusercontent.com/nextauthjs/next-auth/main/docs/static/img/powered-by-vercel.svg" alt="Powered By Vercel" />
</a>
<p align="left">Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire NextAuth.js Team</p>
## License
ISC
<p align="left">Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire Auth.js Team</p>

View File

@@ -1,11 +1,12 @@
import { unstable_getServerSession } from "next-auth/next"
import { getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"
import Layout from "../components/layout"
import type { GetServerSidePropsContext } from "next"
import type { Session } from "next-auth"
import { useSession } from "next-auth/react"
export default function ServerSidePage({ session }: { session: Session }) {
export default function ServerSidePage() {
const { data: session } = useSession()
// As this page uses Server Side Rendering, the `session` will be already
// populated on render without needing to go through a loading stage.
return (
@@ -37,7 +38,7 @@ export default function ServerSidePage({ session }: { session: Session }) {
export async function getServerSideProps(context: GetServerSidePropsContext) {
return {
props: {
session: await unstable_getServerSession(
session: await getServerSession(
context.req,
context.res,
authOptions

View File

@@ -0,0 +1,3 @@
GITHUB_ID=
GITHUB_SECRET=
AUTH_SECRET=

27
apps/examples/solid-start/.gitignore vendored Normal file
View File

@@ -0,0 +1,27 @@
dist
.solid
.output
.vercel
.netlify
netlify
# dependencies
/node_modules
# IDEs and editors
/.idea
.project
.classpath
*.launch
.settings/
# Temp
gitignore
# System Files
.DS_Store
Thumbs.db
.env
.vercel

View File

@@ -0,0 +1,85 @@
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/examples/solid-start). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
<p align="center">
<br/>
<a href="https://authjs.dev" target="_blank">
<img height="64" src="https://authjs.dev/img/logo/logo-sm.png" />
</a>
<a href="https://start.solidjs.com" target="_blank">
<img height="64" src="https://www.solidjs.com/assets/logo-123b04bc.svg" />
</a>
<h3 align="center"><b>SolidStart Auth</b> - Example App</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
<p align="center" style="align: center;">
<a href="https://npm.im/@auth/solid-start">
<img alt="npm" src="https://img.shields.io/npm/v/@auth/solid-start?color=green&label=@auth/solid-start&style=flat-square">
</a>
<a href="https://bundlephobia.com/result?p=@auth/solid-start">
<img src="https://img.shields.io/bundlephobia/minzip/@auth/solid-start?label=size&style=flat-square" alt="Bundle Size"/>
</a>
<a href="https://www.npmtrends.com/@auth/solid-start">
<img src="https://img.shields.io/npm/dm/@auth/solid-start?label=downloads&style=flat-square" alt="Downloads" />
</a>
<a href="https://npm.im/@auth/solid-start">
<img src="https://img.shields.io/badge/TypeScript-blue?style=flat-square" alt="TypeScript" />
</a>
</p>
</p>
## Overview
This is the official SolidStart Auth example for [Auth.js](https://authjs.dev).
## Getting started
You can follow the guide below, or click the following button to deploy this example to [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=solid-start-auth-example).
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/nextauthjs/solid-start-auth-example&project-name=solid-start-auth-example&repository-name=solid-start-auth-example)
### Installing
```sh
pnpm add -D solid-start-vercel
```
```sh
npm i -D solid-start-vercel
```
```sh
yarn add -D solid-start-vercel
```
### Adding to Vite config
```ts
import solid from "solid-start/vite";
import dotenv from "dotenv";
import { defineConfig } from "vite";
// @ts-expect-error no typing
import vercel from "solid-start-vercel";
export default defineConfig(() => {
dotenv.config();
return {
plugins: [solid({ ssr: true, adapter: vercel({ edge: false }) })],
};
});
```
### Environment Variables
- `ENABLE_VC_BUILD`=`1` .
### Finishing up
Create a GitHub repo and push the code to it, then deploy it to Vercel.
## Acknowledgements
<a href="https://vercel.com?utm_source=nextauthjs&utm_campaign=oss">
<img width="170px" src="https://raw.githubusercontent.com/nextauthjs/next-auth/main/docs/static/img/powered-by-vercel.svg" alt="Powered By Vercel" />
</a>
<p align="left">Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire Auth.js Team</p>

View File

@@ -0,0 +1,32 @@
{
"name": "my-app",
"scripts": {
"dev": "solid-start dev",
"build": "solid-start build",
"start": "solid-start start",
"lint": "eslint --fix \"**/*.{ts,tsx,js,jsx}\""
},
"type": "module",
"devDependencies": {
"autoprefixer": "^10.4.13",
"postcss": "^8.4.19",
"solid-start-node": "^0.2.9",
"solid-start-vercel": "^0.2.9",
"tailwindcss": "^3.2.4",
"typescript": "^4.8.3",
"vite": "^3.1.0"
},
"dependencies": {
"@auth/core": "latest",
"@solid-auth/next": "^0.0.19",
"@solidjs/meta": "^0.28.0",
"@solidjs/router": "^0.6.0",
"solid-js": "^1.5.7",
"solid-start": "^0.2.9",
"undici": "5.11.0",
"zod": "^3.19.1"
},
"engines": {
"node": ">=16"
}
}

View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 664 B

View File

@@ -0,0 +1,72 @@
import { Match, Show, Switch, type Component } from "solid-js";
import { createServerData$ } from "solid-start/server";
import { authOpts } from "~/routes/api/auth/[...solidauth]";
import { signIn, signOut } from "@solid-auth/next/client";
import { getSession } from "@solid-auth/next";
import { A } from "solid-start";
interface INavBarProps {}
const NavBar: Component<INavBarProps> = () => {
const session = useSession();
return (
<header class="flex flex-col w-full gap-2 fixed left-2/4 right-2/4 -translate-x-2/4 items-center">
<nav class="w-[70vw] sm:w-2/4 lg:w-[40%] p-5 bg-[#0000000d] flex items-center justify-between rounded-lg">
<Show
when={session()?.user}
keyed
fallback={
<>
<p class="text-lg font-semibold">You are not signed in</p>
<button
class="p-2.5 rounded-lg bg-[#346df1] text-white text-lg font-bold flex items-center justify-center"
onClick={() => signIn("github")}
>
Sign in
</button>
</>
}
>
{(us) => (
<>
<div class="flex gap-2 items-center">
<Show when={us.image} keyed>
{(im) => <img src={im} class="w-12 h-12 rounded-full" />}
</Show>
<div class="flex flex-col">
<h3 class="font-bold text-lg">Signed in as</h3>
<p class="text-lg font-semibold">{us.name}</p>
</div>
</div>
<button
onClick={() => signOut()}
class="text-[#555] font-semibold underline"
>
Sign out
</button>
</>
)}
</Show>
</nav>
<div class="flex gap-2 items-center">
<A class="text-blue-500 font-bold underline" href="/">
Home
</A>
<A class="text-blue-500 font-bold underline" href="/protected">
Protected
</A>
</div>
</header>
);
};
export default NavBar;
export const useSession = () => {
return createServerData$(
async (_, { request }) => {
return await getSession(request, authOpts);
},
{ key: () => ["auth_user"] }
);
};

View File

@@ -0,0 +1 @@
export { default } from "./NavBar";

View File

@@ -0,0 +1,37 @@
import { type Session } from "@auth/core";
import { getSession } from "@solid-auth/next";
import { Component, Show } from "solid-js";
import { useRouteData } from "solid-start";
import { createServerData$, redirect } from "solid-start/server";
import { authOpts } from "~/routes/api/auth/[...solidauth]";
const Protected = (Comp: IProtectedComponent) => {
const routeData = () => {
return createServerData$(
async (_, event) => {
const session = await getSession(event.request, authOpts);
if (!session || !session.user) {
throw redirect("/");
}
return session;
},
{ key: () => ["auth_user"] }
);
};
return {
routeData,
Page: () => {
const session = useRouteData<typeof routeData>();
return (
<Show when={session()} keyed>
{(sess) => <Comp {...sess} />}
</Show>
);
},
};
};
type IProtectedComponent = Component<Session>;
export default Protected;

View File

@@ -0,0 +1 @@
export { default } from "./Protected";

View File

@@ -0,0 +1,2 @@
export { default as NavBar } from "./NavBar";
export { default as Protected } from "./Protected";

View File

@@ -0,0 +1,3 @@
import { mount, StartClient } from "solid-start/entry-client";
mount(() => <StartClient />, document);

View File

@@ -0,0 +1,9 @@
import {
StartServer,
createHandler,
renderAsync,
} from "solid-start/entry-server";
export default createHandler(
renderAsync((event) => <StartServer event={event} />)
);

View File

@@ -0,0 +1,24 @@
import type { ZodFormattedError } from "zod";
import { clientScheme } from "./schema";
export const formatErrors = (
errors: ZodFormattedError<Map<string, string>, string>
) =>
Object.entries(errors)
.map(([name, value]) => {
if (value && "_errors" in value)
return `${name}: ${value._errors.join(", ")}\n`;
})
.filter(Boolean);
const env = clientScheme.safeParse(import.meta.env);
if (env.success === false) {
console.error(
"❌ Invalid environment variables:\n",
...formatErrors(env.error.format())
);
throw new Error("Invalid environment variables");
}
export const clientEnv = env.data;

View File

@@ -0,0 +1,15 @@
import { z } from "zod";
export const serverScheme = z.object({
NODE_ENV: z
.enum(["development", "production", "test"])
.default("development"),
GITHUB_ID: z.string(),
GITHUB_SECRET: z.string(),
AUTH_SECRET: z.string(),
NEXTAUTH_URL: z.string().optional(),
});
export const clientScheme = z.object({
MODE: z.enum(["development", "production", "test"]).default("development"),
});

View File

@@ -0,0 +1,24 @@
import { serverScheme } from "./schema";
import type { ZodFormattedError } from "zod";
export const formatErrors = (
errors: ZodFormattedError<Map<string, string>, string>
) =>
Object.entries(errors)
.map(([name, value]) => {
if (value && "_errors" in value)
return `${name}: ${value._errors.join(", ")}\n`;
})
.filter(Boolean);
const env = serverScheme.safeParse(process.env);
if (env.success === false) {
console.error(
"❌ Invalid environment variables:\n",
...formatErrors(env.error.format())
);
throw new Error("Invalid environment variables");
}
export const serverEnv = env.data;

View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@@ -0,0 +1,40 @@
// @refresh reload
import "./root.css";
import { Suspense } from "solid-js";
import {
Body,
ErrorBoundary,
FileRoutes,
Head,
Html,
Meta,
Routes,
Scripts,
Title,
} from "solid-start";
import { NavBar } from "./components";
export default function Root() {
return (
<Html lang="en">
<Head>
<Title>Create JD App</Title>
<Meta charset="utf-8" />
<Meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<Body>
<Suspense>
<NavBar />
<div class="py-44 px-8">
<ErrorBoundary>
<Routes>
<FileRoutes />
</Routes>
</ErrorBoundary>
</div>
</Suspense>
<Scripts />
</Body>
</Html>
);
}

View File

@@ -0,0 +1,16 @@
import { SolidAuth, type SolidAuthConfig } from "@solid-auth/next";
import GitHub from "@auth/core/providers/github";
import { serverEnv } from "~/env/server";
import { type APIEvent } from "solid-start";
export const authOpts: SolidAuthConfig = {
providers: [
GitHub({
clientId: serverEnv.GITHUB_ID,
clientSecret: serverEnv.GITHUB_SECRET,
}),
],
debug: false,
};
export const { GET, POST } = SolidAuth(authOpts);

View File

@@ -0,0 +1,44 @@
import { type ParentComponent } from "solid-js";
import { A, Title, useRouteData } from "solid-start";
import { createServerData$ } from "solid-start/server";
import { authOpts } from "./api/auth/[...solidauth]";
import { getSession } from "@solid-auth/next";
export const routeData = () => {
return createServerData$(
async (_, { request }) => {
return await getSession(request, authOpts);
},
{ key: () => ["auth_user"] }
);
};
const Home: ParentComponent = () => {
const user = useRouteData<typeof routeData>();
return (
<>
<Title>Create JD App</Title>
<div class="flex flex-col gap-2 items-center">
<h1 class="text-4xl font-bold">SolidStart Auth Example</h1>
<p class="font-semibold text-md max-w-[40rem]">
This is an example site to demonstrate how to use{" "}
<A
href="https://start.solidjs.com/getting-started/what-is-solidstart"
class="text-blue-500 underline font-bold"
>
SolidStart
</A>{" "}
with{" "}
<A
href="https://authjs.dev/reference/solidstart"
class="text-blue-500 underline font-bold"
>
SolidStart Auth
</A>{" "}
for authentication.
</p>
</div>
</>
);
};
export default Home;

View File

@@ -0,0 +1,11 @@
import { Protected } from "~/components";
export const { routeData, Page } = Protected((session) => {
return (
<main class="flex flex-col gap-2 items-center">
<h1>This is a protected route</h1>
</main>
);
});
export default Page;

View File

@@ -0,0 +1,8 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"strict": true,
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"jsxImportSource": "solid-js",
"jsx": "preserve",
"types": ["vite/client"],
"baseUrl": "./",
"paths": {
"~/*": ["./src/*"]
}
}
}

View File

@@ -0,0 +1,10 @@
import solid from "solid-start/vite";
import { defineConfig } from "vite";
// @ts-expect-error no typings
import vercel from "solid-start-vercel";
export default defineConfig(() => {
return {
plugins: [solid({ ssr: true, adapter: vercel({ edge: false }) })],
};
});

View File

@@ -1,9 +1,14 @@
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/example-sveltekit). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/examples/sveltekit). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
<p align="center">
<br/>
<a href="https://authjs.dev" target="_blank"><img width="150px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>
<h3 align="center">Auth.js Example App with <a href="https://kit.svelte.dev">SvelteKit</a></h3>
<a href="https://authjs.dev" target="_blank">
<img height="64" src="https://authjs.dev/img/logo/logo-sm.png" />
</a>
<a href="https://kit.svelte.dev" target="_blank">
<img height="64" src="https://upload.wikimedia.org/wikipedia/commons/1/1b/Svelte_Logo.svg" />
</a>
<h3 align="center"><b>SvelteKit Auth</b> - Example App</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
@@ -11,18 +16,24 @@
<a href="https://npm.im/@auth/sveltekit">
<img alt="npm" src="https://img.shields.io/npm/v/@auth/sveltekit?color=green&label=@auth/sveltekit&style=flat-square">
</a>
<a href="https://bundlephobia.com/result?p=sveltekit-auth-example">
<a href="https://bundlephobia.com/result?p=@auth/sveltekit">
<img src="https://img.shields.io/bundlephobia/minzip/@auth/sveltekit?label=size&style=flat-square" alt="Bundle Size"/>
</a>
<a href="https://www.npmtrends.com/@auth/sveltekit">
<img src="https://img.shields.io/npm/dm/@auth/sveltekit?label=%20downloads&style=flat-square" alt="Downloads" />
<img src="https://img.shields.io/npm/dm/@auth/sveltekit?label=downloads&style=flat-square" alt="Downloads" />
</a>
<a href="https://npm.im/next-auth">
<a href="https://npm.im/@auth/sveltekit">
<img src="https://img.shields.io/badge/TypeScript-blue?style=flat-square" alt="TypeScript" />
</a>
</p>
</p>
# Documentation
## Overview
- [sveltekit.authjs.dev](https://sveltekit.authjs.dev)
This is the official SvelteKit Auth example for [Auth.js](https://sveltekit.authjs.dev).
## Getting started
You can instantly deploy this example to [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=sveltekit-auth-example) by clicking the following button.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/nextauthjs/sveltekit-auth-example&project-name=sveltekit-auth-example&repository-name=sveltekit-auth-example)

View File

@@ -20,10 +20,10 @@
$page.data.session.user?.name}</strong
>
</span>
<a href="/auth/signout" class="button">Sign out</a>
<a href="/auth/signout" class="button" data-sveltekit-preload-data="off">Sign out</a>
{:else}
<span class="notSignedInText">You are not signed in</span>
<a href="/auth/signin" class="buttonPrimary">Sign in</a>
<a href="/auth/signin" class="buttonPrimary" data-sveltekit-preload-data="off">Sign in</a>
{/if}
</p>
</div>

View File

@@ -22,7 +22,7 @@
## Overview
Auth.js is a complete open source authentication solution.
Auth.js is a complete open-source authentication solution.
This is an example application that shows how `@auth/core` is applied to a basic Gatsby app. We are showing how to configure the backend both as a [Vercel Function](https://vercel.com/docs/concepts/functions/introduction) for deployment to Vercel, and also for [Gatsby Functions](https://www.gatsbyjs.com/docs/reference/functions) for other platforms.
@@ -30,7 +30,7 @@ The deployed version can be found at [`next-auth-gatsby-example.vercel.app`](htt
### About Auth.js
Auth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for [Next.js](https://nextjs.org) and [Serverless](https://vercel.com), but this example shows how to use it in a Gatsby project. Our goal is to [support even more frameworks](https://github.com/nextauthjs/next-auth/issues/2294) in the future.
Auth.js is an easy-to-implement, full-stack (client/server) open-source authentication library originally designed for [Next.js](https://nextjs.org) and [Serverless](https://vercel.com), but this example shows how to use it in a Gatsby project. Our goal is to [support even more frameworks](https://github.com/nextauthjs/next-auth/issues/2294) in the future.
Go to [authjs.dev](https://authjs.dev) for more information and documentation.

View File

@@ -10,13 +10,13 @@
"clean": "gatsby clean"
},
"dependencies": {
"dotenv": "^16.0.0",
"gatsby": "next",
"next-auth": "latest",
"react": "^18",
"react-dom": "^18"
"dotenv": "16.0.0",
"gatsby": "5.8.0-next.3",
"next-auth": "workspace:*",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"vercel": "^23.1.2"
"vercel": "23.1.2"
}
}

View File

@@ -2,11 +2,10 @@
"name": "playground-nuxt",
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "export NODE_OPTIONS='--no-experimental-fetch' && nuxt dev",
"build": "nuxt prepare && nuxt build",
"dev": "nuxt prepare && export NODE_OPTIONS='--no-experimental-fetch' && nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
"preview": "nuxt preview"
},
"devDependencies": {
"@nuxt/eslint-config": "^0.1.1",

View File

@@ -174,7 +174,7 @@ If you are deploying directly to a particular cloud platform you may also want t
## Security
Parts of this section has been moved to its [own page](/getting-started/security).
Parts of this section has been moved to its [own page](/security).
<details>
<summary>

View File

@@ -1,56 +0,0 @@
---
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

@@ -1,299 +0,0 @@
---
title: OAuth authentication
---
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**.
:::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 and Gatsby.
:::
## 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.
:::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).
:::
### 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. 💪🏽
:::tip
Check our [client docs](/reference/react/) to learn all the available options for handling sessions on the browser.
:::
### 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.
:::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.
:::
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.
<img 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:
<img 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
```
:::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`.
:::
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:
<img 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).
:::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!
:::
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!
:::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
:::
## 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:
<img 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:
<img 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:
<img src={nextAuthUserLoggedIn} />
Great! We have completed the whole E2E authentication flow setup so that users can login in our application through Github!
:::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.
:::
## 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
```
:::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).
:::
For more information please check out our [deployment page](/guides/basics/deployment).

View File

@@ -46,7 +46,7 @@ export default NextAuth({
```
:::note
Check the [Credentials Provider options](/reference/providers/credentials) for further customization
Check the [Credentials Provider options](/reference/core/providers_credentials) for further customization
:::
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.

View File

@@ -37,7 +37,7 @@ npm install -D nodemailer
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`.
:::info
For this tutorial, we're gonna be using [Sendgrid](https://sendgrid.com/), but any of the services linked above should work the same
For this tutorial, we're going to be using [Sendgrid](https://sendgrid.com/), but any of the services linked above should work the same
:::
First create an account in and then login to the dashboard, then navigate to "Settings → API Keys" and create an API key:
@@ -60,23 +60,23 @@ 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 gonna 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.
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"
import Email from "next-auth/providers/email"
export default NextAuth({
providers: [
Email({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: Number(process.env.EMAIL_SERVER_PORT),
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
from: process.env.EMAIL_FROM,
@@ -147,8 +147,8 @@ import EmailProvider from "next-auth/providers/email"
export default NextAuth({
secret: process.env.NEXTAUTH_SECRET,
+ adapter: MongoDBAdapter(clientPromise),
providers: [
+ adapter: MongoDBAdapter(clientPromise),
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
@@ -170,7 +170,7 @@ Now that everything is properly configured, let's try to sign in via email on ou
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 gonna be using NextAuth example app. Launch the app and click on "Sign in", we're redirected to the Sign In page:
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:
<img src={startPageImg} alt="Screenshot of sign in page" />
@@ -188,7 +188,7 @@ Let's now check our email, and look for one sent from NextAuth (check your spam
<img 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.
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 Sendgrid.
Click on "Sign in" and a new browser tab will open, you should then land on your application as authenticated!

View File

@@ -0,0 +1,44 @@
---
title: Introduction
sidebar_position: 0
---
## About Auth.js
Auth.js is a complete open-source authentication solution for web applications. Check out the live demos of Auth.js in action:
- [Next.js](https://next-auth-example.vercel.app/)
- [SvelteKit](https://sveltekit-auth-example.vercel.app/)
- [SolidStart](https://auth-solid.vercel.app/)
Continue to our tutorials to see how 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)
### Battery included
- Built in support for 60+ popular services (Google, Facebook, Auth0, Apple…)
- Built-in email/password-less/magic link
- Use with any OAuth 2 or OpenID Connect provider
- Use with any username/password store
### Flexible
- Runtime agnostic - run anywhere! Vercel Edge Functions, Node.js, Serverless, etc.
- Use with any modern framework! Next.js, SolidStart, SvelteKit, etc.
- [Bring Your Own Database](/getting-started/databases) - or none! MySQL, Postgres, MSSQL, MongoDB, etc. Choose database sessions or JWT.
_Note: Email sign-in requires a database to store single-use verification tokens._
### Secure by default
- Signed, prefixed, server-only cookies
- Built-in CSRF protection
- Doesn't rely on client-side JavaScript
- JWT with JWS / JWE / JWK.
## Credits
Auth.js is an open-source project that is only possible [thanks to contributors](/contributors).
To financially support the development of Auth.js, you can check our [OpenCollective](https://opencollective.com/nextauth) page. We appreciate your support 💚.

View File

@@ -0,0 +1,369 @@
---
title: OAuth authentication
---
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"
import Tabs from "@theme/Tabs"
import TabItem from "@theme/TabItem"
The goal of Auth.js is that you can add authentication easily to your project with just a few lines of code.
The fastest way to set up Auth.js is with an [OAuth](/concepts/oauth) provider. In this tutorial, we'll be setting Auth.js in a web application to be able to log in with **GitHub**.
:::info
Auth.js comes with a list of [built-in providers](/reference/providers/oauth-builtin) (Google, Facebook, Twitter, etc.). You can also integrate it with your OAuth service by [building a custom provider](/guides/providers/custom-provider).
:::
## 1. Configuring Auth.js
To add Auth.js to your project:
<Tabs groupId="frameworks" queryString>
<TabItem value="next" label="Next.js" default>
### Prerequisites
This tutorial assumes you have a Next.js application set up. If you don't, you can follow the [Next.js tutorial](https://nextjs.org/learn/basics/create-nextjs-app) to get started.
### Installing NextAuth.js
```bash npm2yarn
npm install next-auth
```
:::info
We are working on a new `@auth/nextjs` package that will make it easier to set up Auth.js with Next.js. Stay tuned! For now, you can use the `next-auth` package.
:::
### Creating the server config
Create the following [API route](https://nextjs.org/docs/api-routes/dynamic-api-routes#catch-all-api-routes) file. This route contains the necessary configuration for NextAuth.js, as well as the dynamic route handler:
```ts title="pages/api/auth/[...nextauth].ts"
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,
}),
],
})
```
:::info
Behind the scenes, this creates all the relevant OAuth API routes within `/api/auth/*` so that auth API requests to:
- [GET `/api/auth/signin`](https://authjs.dev/reference/rest-api#get--apiauthsignin)
- [POST `/api/auth/signin/:provider`](https://authjs.dev/reference/rest-api#post--apiauthsigninprovider)
- [GET/POST `/api/auth/callback/:provider`](https://authjs.dev/reference/rest-api#get--post--apiauthcallbackprovider)
- [GET `/api/auth/signout`](https://authjs.dev/reference/rest-api#get--apiauthsignout)
- [POST `/api/auth/signout`](https://authjs.dev/reference/rest-api#post--apiauthsignout)
- [GET `/api/auth/session`](https://authjs.dev/reference/rest-api#get--apiauthsession)
- [GET `/api/auth/csrf`](https://authjs.dev/reference/rest-api#get--apiauthcsrf)
- [GET `/api/auth/providers`](https://authjs.dev/reference/rest-api#get--apiauthproviders)
can be handled by NextAuth.js. In this way, NextAuth.js stays in charge of the whole application's authentication request/response flow.
NextAuth.js is fully customizable - [our guides section](/guides/overview) teaches you how to set it up to handle auth in different ways. All the possible configuration options are [listed here](/reference/configuration/auth-config).
:::
### Adding environment variables
You may notice we are using environment variables in the code example above. We take the value of `GITHUB_ID` and `GITHUB_SECRET` from the GitHub Developer OAuth Portal. See [Configuring OAuth Provider](/getting-started/oauth-tutorial#2-configuring-oauth-provider) section on how to get those.
In your project root, create a `.env.local` file and add the `NEXTAUTH_SECRET` environment variable:
```title=".env.local"
NEXTAUTH_SECRET="This is an example"
```
`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.
### Exposing the session via `SessionProvider`:
NextAuth.js provides [`useSession()`](/reference/react/#usesession) - a [React Hooks](https://reactjs.org/docs/hooks-intro.html) to access the session data and status. To use it first you'll need to expose the session context - [`<SessionProvider />`](/reference/react/#sessionprovider) - at the top level of your application:
```ts title="pages/_app.tsx"
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 have access to the session data and status. The `<SessionProvider />` also keep the session updated and synced between browser tabs and windows. 💪🏽
:::tip
Check our [client docs](/reference/react/) to learn all the available options for handling sessions on the browser.
:::
### Consuming the session via hooks
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. Learn more about React Context in the [React docs](https://reactjs.org/docs/context.html).
```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("github")}>Sign in</button>
</>
)
}
```
### Protecting API Routes
To protect your API Routes (blocking unauthorized access to resources), you can use [`getServerSession()`](/reference/nextjs#getserversession) to know whether a session exists or not:
```ts title="pages/api/movies/list.ts"
import { getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]"
export default async function listMovies(req, res) {
const session = await getServerSession(req, res, authOptions)
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.",
})
}
}
```
</TabItem>
<TabItem value="sveltekit" label="SvelteKit">
TODO: SvelteKit
</TabItem>
<TabItem value="solidstart" label="SolidStart">
TODO: SolidStart
</TabItem>
<TabItem value="core" label="Vanilla (No Framework)">
TODO Core
</TabItem>
</Tabs>
## 2. Configuring OAuth Provider
Ok, we have our app set up with NextAuth.js, however, if you run the app right now, it won't work as we haven't configured our OAuth provider (**GitHub**) yet.
:::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.
:::
We need to register our new app in GitHub, so that when NextAuth.js forwards the authorization requests to it, GitHub can recognize your application and prompt the user to sign in.
<img src={creatingOauthAppImg} />
Log in to **GitHub**, go to [`Settings / Developers / OAuth Apps`](https://github.com/settings/developers) and click "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:
<img 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:
<Tabs groupId="frameworks">
<TabItem value="next" label="Next.js" default>
```
http://localhost:3000/api/auth/callback/github
```
:::info
NextAuth.js will already 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 port `3000` by default. Hence, the origin is `http://localhost:3000`.
:::
</TabItem>
<TabItem value="sveltekit" label="SvelteKit">
```
http://localhost:5173/auth/callback/github
```
</TabItem>
<TabItem value="solidstart" label="SolidStart">
TODO SolidStart
</TabItem>
<TabItem value="core" label="Vanilla (No Framework)">
TODO Core
</TabItem>
</Tabs>
:::info
The last part of the URL, `[provider]`, is the ID of the provider you're using. In this case, we're using GitHub, so it's `github`. If you're using Google, it'll be `google`, etc... We keep track of the provider IDs internally.
The same id is used in the `signIn()` method we saw earlier.
:::
To register, tap on "Register application" button.
The next screen shows all the configurations for your newly created OAuth app. For now, we need two things from it - the **Client ID** and **Client Secret**:
<img 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).
:::warning
Keep both your Client ID and Client Secret secure and never expose them to the public or share them with people outside your organization. With them, a malicious actor could hijack your application and cause you and your user serious problems!
:::
Cool! We have finished configuring our OAuth provider, now let's wire all together so we can finally see authentication working in our app!
:::info
As noted previously, NextAuth.js has built-in support for multiple OAuth providers, <a href="">here is 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
:::
## 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.
Now let's copy both the Client ID and Client Secret and paste them into an environment file in the root of your project like so:
```title=".env.local"
GITHUB_ID=12345
GITHUB_SECRET=67890
```
Here is our server configuration file again:
<Tabs groupId="frameworks">
<TabItem value="next" label="Next.js" default>
```ts title="pages/api/auth/[...nextauth].ts"
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
```
</TabItem>
<TabItem value="sveltekit" label="SvelteKit">
TODO SvelteKit
</TabItem>
<TabItem value="solidstart" label="SolidStart">
TODO SolidStart
</TabItem>
<TabItem value="core" label="Vanilla (No Framework)">
TODO Core
</TabItem>
</Tabs>
You should see the following page:
<img 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:
<img src={githubAuthCredentials} />
Once inserted and correct, GitHub will redirect the user to our app and NextAuth.js will take care of any further calls with GitHub to get access to the user profile and start a user session safely in the background:
<img src={nextAuthUserLoggedIn} />
Great! We have completed the whole E2E authentication flow setup so that users can log in to our application through GitHub!
## 4. Deploying to production
### Configuring different environments
It's normal to test your application in different environments. Usually, you'll have a development environment (when you run the application locally on your machine), a staging environment (for team members to try the application), and a production environment.
For each environment, you 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 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 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 with.
### Setting up `NEXTAUTH_URL`
:::tip
Skip this section if you are deploying to Vercel.
:::
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
```
:::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).
:::
For more information please check out our [deployment page](/guides/basics/deployment).

View File

@@ -5,7 +5,7 @@ title: TypeScript
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
https://github.com/nextauthjs/next-auth-example
---

View File

@@ -239,7 +239,7 @@ Introduced in https://github.com/nextauthjs/next-auth/releases/tag/v4.0.0-next.1
## `nodemailer`
Like `typeorm` and `prisma`, [`nodemailer`](https://npmjs.com/package/nodemailer) is no longer included as a dependency by default. If you are using the Email provider you must install it in your project manually, or use any other Email library in the [`sendVerificationRequest`](/reference/providers/email) callback. This reduces bundle size for those not actually using the Email provider. Remember, when using the Email provider, it is mandatory to also use a database adapter due to the fact that verification tokens need to be persisted longer term for the magic link functionality to work.
Like `typeorm` and `prisma`, [`nodemailer`](https://npmjs.com/package/nodemailer) is no longer included as a dependency by default. If you are using the Email provider you must install it in your project manually, or use any other Email library in the [`sendVerificationRequest`](/guides/providers/email) callback. This reduces bundle size for those not actually using the Email provider. Remember, when using the Email provider, it is mandatory to also use a database adapter due to the fact that verification tokens need to be persisted longer term for the magic link functionality to work.
Introduced in https://github.com/nextauthjs/next-auth/releases/tag/v4.0.0-next.2

View File

@@ -1,136 +0,0 @@
---
title: Refresh token rotation
---
While Auth.js doesn't automatically handle access token rotation for [OAuth providers](/reference/providers/oauth-builtin) yet, this functionality can be implemented using [callbacks](/guides/basics/callbacks).
## Source Code
A working example can be accessed [here](https://github.com/nextauthjs/next-auth-refresh-token-example).
## Implementation
### Server Side
Using a [JWT callback](https://authjs.dev/guides/basics/callbacks#jwt-callback) and a [session callback](https://authjs.dev/guides/basics/callbacks#session-callback), 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.
```js title="pages/api/auth/[...nextauth].js"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
const GOOGLE_AUTHORIZATION_URL =
"https://accounts.google.com/o/oauth2/v2/auth?" +
new URLSearchParams({
prompt: "consent",
access_type: "offline",
response_type: "code",
})
/**
* Takes a token, and returns a new token with updated
* `accessToken` and `accessTokenExpires`. If an error occurs,
* returns the old token and an error property
*/
async function refreshAccessToken(token) {
try {
const url =
"https://oauth2.googleapis.com/token?" +
new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: token.refreshToken,
})
const response = await fetch(url, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
})
const refreshedTokens = await response.json()
if (!response.ok) {
throw refreshedTokens
}
return {
...token,
accessToken: refreshedTokens.access_token,
accessTokenExpires: Date.now() + refreshedTokens.expires_at * 1000,
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshAccessTokenError",
}
}
}
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: GOOGLE_AUTHORIZATION_URL,
}),
],
callbacks: {
async jwt({ token, user, account }) {
// Initial sign in
if (account && user) {
return {
accessToken: account.access_token,
accessTokenExpires: Date.now() + account.expires_at * 1000,
refreshToken: account.refresh_token,
user,
}
}
// Return previous token if the access token has not expired yet
if (Date.now() < token.accessTokenExpires) {
return token
}
// Access token has expired, try to update it
return refreshAccessToken(token)
},
async session({ session, token }) {
session.user = token.user
session.accessToken = token.accessToken
session.error = token.error
return session
},
},
})
```
### Client Side
The `RefreshAccessTokenError` error that is caught in the `refreshAccessToken()` method is passed all the way 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 (...)
}
```

View File

@@ -1,64 +0,0 @@
---
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

@@ -1,136 +0,0 @@
---
title: Using a custom Provider
sidebar_label: Creating a Provider
---
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.
:::note
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.
:::
```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

@@ -1,5 +0,0 @@
{
"label": "Other",
"collapsible": true,
"collapsed": true
}

View File

@@ -1,79 +0,0 @@
---
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

@@ -1,60 +0,0 @@
---
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

@@ -10,4 +10,4 @@ When using a database, you can still use JWT for session handling for fast acces
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)
- [All available adapters](/reference/adapters)

View File

@@ -1,5 +1,5 @@
{
"label": "Basics",
"collapsible": true,
"collapsed": true
"collapsed": false
}

View File

@@ -60,7 +60,7 @@ Example: `/auth/signin?error=Default`
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 a `theme.brandColor` to define a custom accent color for these built-in pages. You can also define a URL to a logo in `theme.logo` which will be rendered above the primary card in these pages.
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

View File

@@ -0,0 +1,225 @@
---
title: Refresh token rotation
---
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.
:::note
Our goal is to add zero-config support for built-in providers eventually. Let us know if you would like to help.
:::
## 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.
:::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.
:::
#### JWT strategy
Using the [jwt](../../reference/core/types#jwt) and [session](../../reference/core/types#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: Math.floor(Date.now() / 1000 + account.expires_in),
refresh_token: account.refresh_token,
}
} else if (Date.now() < token.expires_at * 1000) {
// 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: Math.floor(Date.now() / 1000 + tokens.expires_in),
// 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 * 1000 < 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: Math.floor(Date.now() / 1000 + tokens.expires_in),
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,153 @@
---
title: Role-based access control
---
There are two ways to add role-based access control (RBAC) to your application, based on the [session strategy](/concepts/session-strategies) you choose. Let's see an example for each of these.
## Getting the role
We are going to start by adding a `profile()` callback to the providers' config to determine the user role:
```ts title="/pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
export default NextAuth({
providers: [
Google({
profile(profile) {
return { role: profile.role ?? "user", ... }
},
...
})
],
})
```
:::tip
To determine the user's role, you can either add your logic or if your provider assigns roles already, use that instead.
:::
## Persisting the role
### With JWT
When you don't have a database configured, the role will be persisted in a cookie, by using the `jwt()` callback. On sign-in, the `role` property is exposed from the `profile` callback on the `user` object. Persist the `user.role` value by assigning it to `token.role`. That's it!
If you also want to use the role on the client, you can expose it via the `session` callback.
```ts title="/pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
export default NextAuth({
providers: [
Google({
profile(profile) {
return { role: profile.role ?? "user", ... }
},
...
})
],
// highlight-start
callbacks: {
jwt({ token, user }) {
if(user) token.role = user.role
return token
},
session({ session, token }) {
session.user.role = token.role
return session
}
}
// highlight-end
})
```
:::info
With this strategy, if you want to update the role, the user needs to be forced to sign in again.
:::
### With Database
When you have a database, you can save the user role on the [User model](/reference/adapters/models#user). The below example is showing you how to do this with Prisma, but the idea is the same for all adapters.
First, add a `role` column to the User model.
```ts 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[]
}
```
The `profile()` callback's return value is used to create users in the database. That's it! Your newly created users will now have an assigned role.
If you also want to use the role on the client, you can expose it via the `session` callback.
```ts title="/pages/api/auth/[...nextauth].ts"
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
// highlight-next-line
import prisma from "lib/prisma"
export default NextAuth({
// highlight-next-line
adapter: PrismaAdapter(prisma),
providers: [
Google({
profile(profile) {
return { role: profile.role ?? "user", ... }
}
...
})
],
// highlight-start
callbacks: {
session({ session, user }) {
session.user.role = user.role
return session
}
}
// highlight-end
})
```
:::info
It is up to you how you want to manage to update the roles, either through direct database access or building your role update API.
:::
## Using the role
If you want to use the role in the client, for both cases above, when using the `useSession` hook, `session.user.role` will have the required role if you exposed it via the `session` callback. You can use this to render a different UI for different users.
```ts title="/pages/admin.tsx"
import { useSession } from "next-auth/react"
export default function Page() {
const session = await useSession()
if (session?.user.role === "admin") {
return <p>You are an admin, welcome!</p>
}
return <p>You are not authorized to view this page!</p>
}
```
:::tip
When using Next.js and JWT, you can alternatively also use [Middleware](https://next-auth.js.org/configuration/nextjs#wrap-middleware) to redirect the user based on their role, even before rendering the page.
:::
## Resources
- [Concepts: Session strategies](/concepts/session-strategies)
- [Next.js: Middleware](https://next-auth.js.org/configuration/nextjs#wrap-middleware)
- [Adapters: User model](/reference/adapters/models#user)
- [Adapters: Prisma adapter](/reference/adapters/prisma)
- [TypeScript](/getting-started/typescript)

View File

@@ -2,7 +2,7 @@
title: Corporate proxy
---
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:
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 proxies 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)

View File

@@ -1,9 +1,12 @@
---
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.
This section contains guides for common use cases.
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).
If you can't find what you're looking for, [raise an issue](https://github.com/nextauthjs/next-auth/issues/new?assignees=&labels=triage%2Cdocumentation&template=4_documentation.yml).
:::warning Warning
Guides are being migrated from the [old documentation page](https://next-auth.js.org), so there are going to be references to `next-auth` still. We are continuously working on updating the naming/references.
:::

View File

@@ -3,21 +3,21 @@ id: credentials
title: Credentials Provider
---
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).
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.
:::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.
The functionality provided for credentials-based authentication is intentionally limited to discourage the use of passwords due to the inherent security risks associated with them and the additional complexity associated with supporting usernames and passwords.
:::
## Options
The **Credentials Provider** comes with a set of default options:
- [Credentials Provider options](/reference/providers/credentials)
- [Credentials Provider options](/reference/core/providers_credentials)
You can override any of the options to suit your own use case.
@@ -33,7 +33,7 @@ If you return an object it will be persisted to the JSON Web Token and the user
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).
The Credentials provider's `authorize()` method also provides the request object as the second parameter (see the example below).
```js title="pages/api/auth/[...nextauth].js"
import CredentialsProvider from "next-auth/providers/credentials";
@@ -89,7 +89,7 @@ You can specify more than one credentials provider by specifying a unique `id` f
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.
As with all providers, the order you specify is the order they are displayed on the sign-in page.
```js
providers: [

View File

@@ -0,0 +1,112 @@
---
title: OAuth Provider
---
Auth.js comes with a set of built-in OAuth providers that you can import from `@auth/core/providers/*`. Every provider has their separate documentation page under the [core package's API Reference](/reference/core)
## Use your own provider
However, you can use _any_ provider as long as they are compliant with the OAuth/OIDC specifications.
Auth.js uses the [`oauth4webapi`](https://github.com/panva/oauth4webapi/blob/main/docs/README.md) package under the hood.
To use a custom OAuth provider with Auth.js, pass an object to the [`providers` list](/reference/core#providers).
It can implement either the [`OAuth2Config`](/reference/core/providers#oauth2configprofile) or the [`OIDCConfig`](/reference/core/providers#oidcconfigprofile) interface, depending on if your provider is OAuth 2 or OpenID Connect compliant.
For example, if you have a fully OIDC-compliant provider, this is all you need:
```ts
import type { OIDCConfig } from "@auth/core/providers"
...
providers: [
{
id: "my-oidc-provider",
name: "My Provider",
type: "oidc",
issuer: "https://my.oidc-provider.com",
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET
} satisfies OIDCConfig
]
...
```
Then, you can set the [Redirect URI](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-07.html#name-client-redirection-endpoint) in your provider's dashboard to something like `https://app-url.com/{path-to-auth-handler}/callback/my-oidc-provider`.
`{path-to-auth-handler}` is _usually_ `auth` or `api/auth`, depending on your framework of your choice.
`my-oidc-provider` matches the `id` you set in the [`providers` list](/reference/core#providers).
## Override default provider config
For built-in providers, in most cases you will only need to specify the `clientId` and `clientSecret`, and in case of OIDC providers, the `issuer` property. If you need to override any of the defaults, you can add them in the provider's function call and they will be deep-merged with the default configuration options.
:::note
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.
:::
For example, to override a provider's default scopes, you can do the following:
```ts
import Auth0Provider from "@auth/core/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 want to return more information from the provider. After setting the correct scopes, you can then do something like this:
```ts
import GoogleProvider from "@auth/core/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:
```ts
import GoogleProvider from "@auth/core/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.
:::note
We are only accepting new providers to `@auth/core`, and not `next-auth`. Follow the steps below to make sure your PR is merged!
:::
1. Create a new `{provider}.ts` (for it to get merged, you must use TypeScript) file under the [`packages/core/src/providers`](https://github.com/nextauthjs/next-auth/tree/main/packages/core/src/providers) directory.
2. Make sure that you are following other providers, ie.:
- Use a named default export: `export default function YourProvider`
- Export the TypeScript `interface` that defines the provider's available user info properties
- Add the necessary JSDoc comments/documentation (Study the built-in providers to get an understanding what's needed. For example, the [Auth0 provider](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/auth0.ts) is a good example for OIDC and the [GitHub Provider](https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/providers/github.ts) is an OAuth provider.)
- Add links to the provider's API reference/documentation so others can understand how to use the provider
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)
4. (Optional): Add a logo `{provider}.svg` to the [`docs/static/img/providers`](https://github.com/nextauthjs/next-auth/tree/main/docs/static/img/providers) directory.
That's it! 🎉 Others will be able to discover and use this provider!

View File

@@ -0,0 +1,109 @@
---
id: email-http
title: HTTP-based Email Provider
---
## Introduction
:::note
The following guide is written for `next-auth` (NextAuth.js), but it should work for any of the Auth.js framework libraries (`@auth/*`) as well.
:::
There is a built-in Email provider with which you could connect to the SMTP server of your choice to send "magic link" emails for sign-in purposes. However, the Email provider can also be used with HTTP-based email services, like AWS SES, Postmark, Sendgrid, etc. In this guide, we are going to explain how to use our Email magic link provider with any of the more modern HTTP-based Email APIs.
For this example, we will be using [SendGrid](https://sendgrid.com), but any email service providing an HTTP API or JS client library will work.
We will also refer to the [Prisma Adapter](/reference/adapter/prisma). A [database adapter](/adapters/overview) is a requirement for the Email provider.
## Setup
First, if you do not have a project using Auth.js, clone and set up a basic Auth.js project like the one [provided in](https://github.com/nextauthjs/next-auth-example.git) our example repo](https://github.com/nextauthjs/next-auth-example.git).
- Install the [Prisma Adapter](/reference/adapter/prisma)
- Generate an API key from your cloud Email provider of choice and add it to your `.env.*` file. For example, mine is going to be called `SENDGRID_API`
- Add the following configuration to your configuration file:
```js title="pages/api/auth/[...nextauth].ts"
import NextAuth, { NextAuthOptions } from "next-auth"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
{
id: 'sendgrid',
type: 'email',
async sendVerificationRequest({identifier: email, url}) {
}
}
],
}
export default NextAuth(authOptions)
```
Next, all that's left to do is call the HTTP endpoint from our cloud email provider and pass it the required metadata like the `to` address, the email `body`, and any other fields we may need to include.
As mentioned earlier, we're going to be using SendGrid in this example, so the appropriate endpoint is `https://api.sendgrid.com/v3/mail/send` ([more info](https://docs.sendgrid.com/for-developers/sending-email/api-getting-started)). Therefore, we're going to pull out some of the important information from the `params` argument and use it in a `fetch()` call to the previously mentioned SendGrid API.
```js title="pages/api/auth/[...nextauth].ts"
import NextAuth, { NextAuthOptions } from "next-auth"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
{
id: 'sendgrid',
type: 'email',
async sendVerificationRequest({identifier: email, url}) {
// highlight-start
// Call the cloud Email provider API for sending emails
// See https://docs.sendgrid.com/api-reference/mail-send/mail-send
const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
// The body format will vary depending on provider, please see their documentation
// for further details.
body: JSON.stringify({
personalizations: [{ to: [{ email }] }],
from: { email: "noreply@company.com" },
subject: "Sign in to Your page",
content: [
{
type: "text/plain",
value: `Please click here to authenticate - ${url}`,
},
],
}),
headers: {
// Authentication will also vary from provider to provider, please see their docs.
Authorization: `Bearer ${process.env.SENDGRID_API}`,
"Content-Type": "application/json",
},
method: "POST",
})
if (!response.ok) {
const { errors } = await response.json()
throw new Error(JSON.stringify(errors))
}
// highlight-end
},
}
],
}
```
And that's all we need to do to send Emails via an HTTP API! Note here that the example is only using `text/plain` as the body type. You'll probably want to change that to `text/html` and pass in a nice-looking HTML email. See, for example, our `html` function in [the Auth.js docs](/providers/email#customizing-emails).
To sign in via this custom provider, you would refer to it by the `id` in when you are calling the sign-in method, for example: `signIn('sendgrid', { email: 'user@company.com' })`.
## References
- [Email provider documentation with HTML generation and more](/reference/core/modules/providers_email)
- [SendGrid JSON Body documentation](https://docs.sendgrid.com/api-reference/mail-send/mail-send#body)

View File

@@ -23,7 +23,7 @@ The Email Provider can be used with both JSON Web Tokens and database sessions,
The **Email Provider** comes with a set of default options:
- [Email Provider options](/reference/providers/email)
- [Email Provider options](/guides/providers/email)
You can override any of the options to suit your own use case.

View File

@@ -1,447 +0,0 @@
---
title: Initialization
---
## 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.
:::warning
Not providing any `secret` or `NEXTAUTH_SECRET` will throw [an error](/reference/errors#no_secret) in production.
:::
You can quickly create a good value on the command line via this `openssl` command.
```bash
$ openssl rand -base64 32
```
:::tip
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.
:::
---
### 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.
:::note
The JWT is stored in the Session Token cookie, the same cookie used for tokens with database sessions.
:::
---
### 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)
}
```
:::note
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`.
:::
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)
}
}
...
})
```
:::note
If the `debug` level is defined by the user, it will be called regardless of the `debug: false` [option](#debug).
:::
---
### 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.
:::note
Properties on any custom `cookies` that are specified override this option.
:::
:::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.
:::
---
### 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.
:::tip
An example of a use case for this option is to support sharing session tokens across subdomains.
:::
#### 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
},
},
}
```
:::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.
:::

View File

@@ -1,38 +0,0 @@
---
title: Environment variables
sidebar_label: Environment Variables
---
## 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`_
:::note
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.
:::
---
## 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

@@ -1,5 +0,0 @@
{
"label": "Configuration",
"collapsible": true,
"collapsed": true
}

View File

@@ -1,271 +0,0 @@
---
id: client
title: Utilities
---
The Auth.js client library makes it easy to interact with sessions from React applications.
#### Example Session Object
```ts
{
user: {
name: string
email: string
image: string
},
expires: Date // This is the expiry of the session, not any of the tokens within the session
}
```
:::tip
The session data returned to the client does not contain sensitive information such as the Session Token or OAuth tokens. It contains a minimal payload that includes enough data needed to display information on a page about the user who is signed in for presentation purposes (e.g name, email, image).
You can use the [session callback](/reference/configuration/auth-config#callbacks) to customize the session object returned to the client if you need to return additional data in the session object.
:::
:::note
The `expires` value is rotated, meaning whenever the session is retrieved from the [REST API](/reference/rest-api), this value will be updated as well, to avoid session expiry.
:::
## getSession()
- Client Side: **Yes**
- Server Side: **No** (See: [`unstable_getServerSession()`](/reference/nextjs/#unstable_getserversession)
Auth.js provides a `getSession()` helper which should be called **client side only** to return the current active session.
On the server side, **this is still available to use**, however, we recommend using `unstable_getServerSession` going forward. The idea behind this is to avoid an additional unnecessary `fetch` call on the server side. For more information, please check out [this issue](https://github.com/nextauthjs/next-auth/issues/1535).
:::note
The `unstable_getServerSession` only has the prefix `unstable_` at the moment, because the API may change in the future. There are no known bugs at the moment and it is safe to use. If you discover any issues, please do report them as a [GitHub Issue](https://github.com/nextauthjs/next-auth/issues) and we will patch them as soon as possible.
:::
This helper is helpful in case you want to read the session outside of the context of React.
When called, `getSession()` will send a request to `/api/auth/session` and returns a promise with a [session object](https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/core/types.ts#L407-L425), or `null` if no session exists.
```js
async function myFunction() {
const session = await getSession()
/* ... */
}
```
Read the tutorial [securing pages and API routes](/guides/basics/securing-pages-and-api-routes) to know how to fetch the session in server side calls using `unstable_getServerSession()`.
---
## getCsrfToken()
- Client Side: **Yes**
- Server Side: **Yes**
The `getCsrfToken()` method returns the current Cross Site Request Forgery Token (CSRF Token) required to make POST requests (e.g. for signing in and signing out).
You likely only need to use this if you are not using the built-in `signIn()` and `signOut()` methods.
#### Client Side Example
```js
async function myFunction() {
const csrfToken = await getCsrfToken()
/* ... */
}
```
#### Server Side Example
```js
import { getCsrfToken } from "next-auth/react"
export default async (req, res) => {
const csrfToken = await getCsrfToken({ req })
/* ... */
res.end()
}
```
---
## getProviders()
- Client Side: **Yes**
- Server Side: **Yes**
The `getProviders()` method returns the list of providers currently configured for sign in.
It calls `/api/auth/providers` and returns a list of the currently configured authentication providers.
It can be useful if you are creating a dynamic custom sign in page.
---
#### API Route
```jsx title="pages/api/example.js"
import { getProviders } from "next-auth/react"
export default async (req, res) => {
const providers = await getProviders()
console.log("Providers", providers)
res.end()
}
```
:::note
Unlike and `getCsrfToken()`, when calling `getProviders()` server side, you don't need to pass anything, just as calling it client side.
:::
---
## signIn()
- Client Side: **Yes**
- Server Side: No
Using the `signIn()` method ensures the user ends back on the page they started on after completing a sign in flow. It will also handle CSRF Tokens for you automatically when signing in with email.
The `signIn()` method can be called from the client in different ways, as shown below.
### Redirects to sign in page when clicked
```js
import { signIn } from "next-auth/react"
export default () => <button onClick={() => signIn()}>Sign in</button>
```
### Starts OAuth sign-in flow when clicked
By default, when calling the `signIn()` method with no arguments, you will be redirected to the Auth.js sign-in page. If you want to skip that and get redirected to your provider's page immediately, call the `signIn()` method with the provider's `id`.
For example to sign in with Google:
```js
import { signIn } from "next-auth/react"
export default () => (
<button onClick={() => signIn("google")}>Sign in with Google</button>
)
```
### Starts Email sign-in flow when clicked
When using it with the email flow, pass the target `email` as an option.
```js
import { signIn } from "next-auth/react"
export default ({ email }) => (
<button onClick={() => signIn("email", { email })}>Sign in with Email</button>
)
```
### Specifying a `callbackUrl`
The `callbackUrl` specifies to which URL the user will be redirected after signing in. Defaults to the page URL the sign-in is initiated from.
You can specify a different `callbackUrl` by specifying it as the second argument of `signIn()`. This works for all providers.
e.g.
- `signIn(undefined, { callbackUrl: '/foo' })`
- `signIn('google', { callbackUrl: 'http://localhost:3000/bar' })`
- `signIn('email', { email, callbackUrl: 'http://localhost:3000/foo' })`
The URL must be considered valid by the [redirect callback handler](/reference/configuration/auth-config#callbacks). By default it requires the URL to be an absolute URL at the same host name, or a relative url starting with a slash. If it does not match it will redirect to the homepage. You can define your own [redirect callback](/guides/basics/callbacks#redirect-callback) to allow other URLs.
### Using the `redirect: false` option
:::note
The redirect option is only available for `credentials` and `email` providers.
:::
In some cases, you might want to deal with the sign in response on the same page and disable the default redirection. For example, if an error occurs (like wrong credentials given by the user), you might want to handle the error on the same page. For that, you can pass `redirect: false` in the second parameter object.
e.g.
- `signIn('credentials', { redirect: false, password: 'password' })`
- `signIn('email', { redirect: false, email: 'bill@fillmurray.com' })`
`signIn` will then return a Promise, that resolves to the following:
```ts
{
/**
* Will be different error codes,
* depending on the type of error.
*/
error: string | undefined
/**
* HTTP status code,
* hints the kind of error that happened.
*/
status: number
/**
* `true` if the signin was successful
*/
ok: boolean
/**
* `null` if there was an error,
* otherwise the url the user
* should have been redirected to.
*/
url: string | null
}
```
### Additional parameters
It is also possible to pass additional parameters to the `/authorize` endpoint through the third argument of `signIn()`.
See the [Authorization Request OIDC spec](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest) for some ideas. (These are not the only possible ones, all parameters will be forwarded)
e.g.
- `signIn("identity-server4", null, { prompt: "login" })` _always ask the user to re-authenticate_
- `signIn("auth0", null, { login_hint: "info@example.com" })` _hints the e-mail address to the provider_
:::note
You can also set these parameters through [`provider.authorizationParams`](/reference/providers/oauth).
:::
:::note
The following parameters are always overridden server-side: `redirect_uri`, `state`
:::
---
## signOut()
- Client Side: **Yes**
- Server Side: No
In order to logout, use the `signOut()` method to ensure the user ends back on the page they started on after completing the sign out flow. It also handles CSRF tokens for you automatically.
It reloads the page in the browser when complete.
```js
import { signOut } from "next-auth/react"
export default () => <button onClick={() => signOut()}>Sign out</button>
```
### Specifying a `callbackUrl`
As with the `signIn()` function, you can specify a `callbackUrl` parameter by passing it as an option.
e.g. `signOut({ callbackUrl: 'http://localhost:3000/foo' })`
The URL must be considered valid by the [redirect callback handler](/guides/basics/callbacks#redirect-callback). By default, it requires the URL to be an absolute URL at the same host name, or you can also supply a relative URL starting with a slash. If it does not match it will redirect to the homepage. You can define your own [redirect callback](/guides/basics/callbacks#redirect-callback) to allow other URLs.
### Using the `redirect: false` option
If you pass `redirect: false` to `signOut`, the page will not reload. The session will be deleted, and the `useSession` hook is notified, so any indication about the user will be shown as logged out automatically. It can give a very nice experience for the user.
:::tip
If you need to redirect to another page but you want to avoid a page reload, you can try:
`const data = await signOut({redirect: false, callbackUrl: "/foo"})`
where `data.url` is the validated URL you can redirect the user to without any flicker by using Next.js's `useRouter().push(data.url)`
:::

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