Authentication for Next.js

Overview


NextAuth.js

Authentication for Next.js

Open Source. Full Stack. Own Your Data.

Release Integration Test Bundle Size Downloads Github Stars Github Stable Release Github Prelease

Overview

NextAuth.js is a complete open source authentication solution for Next.js applications.

It is designed from the ground up to support Next.js and Serverless.

Getting Started

npm install --save next-auth

The easiest way to continue getting started, is to follow the getting started section in our docs.

We also have a section of tutorials for those looking for more specific examples.

See next-auth.js.org for more information and documentation.

Features

Flexible and easy to use

  • Designed to work with any OAuth service, it supports OAuth 1.0, 1.0A and 2.0
  • Built-in support for many popular sign-in services
  • Supports email / passwordless authentication
  • Supports stateless authentication with any backend (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

NextAuth.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, Microsoft SQL Server, MongoDB and SQLite
  • Works great with databases from popular hosting providers
  • Can also be used without a database (e.g. OAuth + JWT)

Secure by default

  • Promotes the use of passwordless sign in mechanisms
  • Designed to be secure by default and encourage best practice 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 signed by default (JWS) with HS512
  • Use JWT encryption (JWE) by setting the option encryption: true (defaults to 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

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 is able to sign in and how often sessions have to be re-validated.

TypeScript

You can install the appropriate types via the following command:

npm install --save-dev @types/next-auth

As of now, TypeScript is a community effort. If you encounter any problems with the types package, please create an issue at DefinitelyTyped. Alternatively, you can open a pull request directly with your fixes there. We welcome anyone to start a discussion on migrating this package to TypeScript, or how to improve the TypeScript experience in general.

Example

Add API Route

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

export default NextAuth({
  providers: [
    // OAuth authentication providers
    Providers.Apple({
      clientId: process.env.APPLE_ID,
      clientSecret: process.env.APPLE_SECRET
    }),
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    }),
    // Sign in with passwordless email link
    Providers.Email({
      server: process.env.MAIL_SERVER,
      from: '<[email protected]>'
    }),
  ],
  // SQL or MongoDB database (or leave empty)
  database: process.env.DATABASE_URL
})

Add React Component

import {
  useSession, signIn, signOut
} from 'next-auth/client'

export default function Component() {
  const [ session, loading ] = useSession()
  if(session) {
    return <>
      Signed in as {session.user.email} <br/>
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

Acknowledgements

NextAuth.js is made possible thanks to all of its contributors.

Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire NextAuth.js Team

Contributing

We're open to all community contributions! If you'd like to contribute in any way, please first read our Contributing Guide.

License

ISC

Issues
  • πŸ“’ NextAuth.js 2.0 Announcement

    πŸ“’ NextAuth.js 2.0 Announcement

    Announcement

    A lot has changed in Next.js since NextAuth 1.0 was released.

    Now.sh, Vercel (formerly known Zeit), React and Node.js have also evolved a lot of the last couple of years.

    This has made for a difficult moving target and so ,due the dramatic nature of those changes over the last year, feature development was paused on NextAuth (with the exception of minor maintenance updates for security).

    With API routes introduced in Next.js 9.0 and Serverless deployments now the default on Now.sh (and widely supported on AWS, GPC and Azure) it's time for an update.

    Authentication continues to be a pain point for a lot of folks. oAuth standardisation has improved, but common providers (Twitter, Facebook, Google, GitHub) all continue to have divergent implementations.

    Lessons learned from 1.x and feedback dozens of issues and left by hundreds of people has gone into version 2.0 to try and take the pain out of setup and configuration, and to provide a solution that works for more people by improving the backend database support.

    I'd like to thank everyone who raised issues, left feedback, helped out other folks when I didn't have time to get back to people, and to all those folks who raised pull requests (for all those that don't get merged in, please know they were not in vain, they've been invaluable!).

    Version 2.0 is expected to drop sometime in May 2020, with releases will be published to [email protected] starting the first week of May. Feel free to ask questions or make requests below.

    * NextAuth is not associated with Next.js or Vercel.

    What's new

    Version 2.0 is a complete re-write, designed from the ground up for serverless.

    • Built for Serverless - unlike version 1.x it doesn't depend on Express or PassportJS (but is compatible with them) and is designed to support automatic code splitting at build time for optimal bundle size and performance.
    • Supports the same oAuth 1.x and oAuth 2.x and email authentication flows as version 1.x (both client and server side).
    • Simple configuration with out-of-the-box support for common oAuth providers and databases.

    If you are familiar with version 1.x you will appreciate the much simpler and hassle free configuration, especially for provider configuration, database adapters and much improved Cross Site Request Forgery token handling (now enabled by default for next-auth routes only).

    Additional options and planned features will be announced closer to release.

    What to expect

    Configuration is much simpler and more powerful than in NextAuth 1.0, with both SQL and Document databases supported out of the box. There are predefined models for Users and Sessions, which you can use (or extend or replace with your own models/schemas).

    Server

    To add next-auth to a project, create a file to handle authentication requests at pages/api/auth/[...slug.js]:

    import NextAuth from 'next-auth'
    import Providers from 'next-auth/providers'
    import Adapters from 'next-auth/adapters'
    
    const options = {
      site: process.env.SITE_NAME || 'http://localhost:3000',
      providers: [
        Providers.Twitter({
          clientId: process.env.TWITTER_CLIENT_ID,
          clientSecret: process.env.TWITTER_CLIENT_SECRET,
        }),
        Providers.Google({
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET
        }),
        Providers.GitHub({
          clientId: process.env.GITHUB_CLIENT_ID,
          clientSecret: process.env.GITHUB_CLIENT_SECRET
        }),
      ],
      adapter: Adapters.Default()
    }
    
    export default (req, res) => NextAuth(req, res, options)
    

    All requests to pages/api/auth/* (signin, callback, signout) will now be automatically handed by NextAuth.

    Client

    You can now use the can use the useSession() hook to see if a user is signed in.

    import NextAuth from 'next-auth/client'
    
    export default () => {
      const [session, loading] = NextAuth.useSession()
    
      return <>
        {!loading && session && <p>Logged in as {session.user.name || session.user.email}.</p>}
        {!loading && !session && <p>Not logged in.</p>}
      </>
    }
    

    This is all the code you need to add support for signing in to a project!

    Server Side Rendering

    Authentication with Server Side Rendering is also supported.

    import NextAuth from 'next-auth/client'
    
    export default ({ session }) => <>
      {session && <p>You are logged in as {session.user.name || session.user.email}.</p>}
      {!session && <p>You are not logged in.</p>}
    </>
    
    export async function getServerSideProps({req}) {
      const session = await NextAuth.session({req})
      return {
        props: {
          session
        }
      }
    }
    

    You can use this method and the useSession() hook together - the hook can be pre-populated with the session object from the server side call, so that it is avalible immediately when the page is loaded, and updated client side when the page is viewed in the browser.

    You can also call NextAuth.session() function in client side JavaScript, without needing to pass a req object (it is only needed when calling the function from getServerSideProps or getInitialProps).

    Authentication between the client and server is handled securely, using an HTTP only cookie for the session ID.

    Important! The API for 2.0 is subject to change before release.

    Configuration

    Configuration options are passed to NextAuth when initalizing it (in your /api/ route).

    The only things you will probably need to configure are your site name (e.g. 'http://www.example.com'), which should be set explicitly for security reasons, a list of authentication services (Twitter, Facebook, Google, etc) and a database adapter.

    An "Adapter" in NextAuth is the thing that connects your application to whatever system you want to use to store data for user accounts, sessions, etc. NextAuth comes with a default adapter that uses TypeORM so that it can be be used with many different databases without any configuration, you simply add the database driver you want to use to your project and tell NextAuth to use it.

    Simple Example

    To use SQLite in memory database (useful for development and testing, and to check everything is working):

    1. Install the database driver as a dependancy in the usual way - e.g. npm i sqlite3
    2. Pass a TypeORM configuration object when calling NextAuth() in your API route.

    e.g.

    adapter: Adapters.Default({
      type: 'sqlite',
      database: ':memory:'
    }),
    

    You can pass database credentials here securely, using environment variables in your application.

    See the TypeORM configuration documentation for more details about supported options.

    Customization

    NextAuth now auto-generates simple, unbranded authentication pages for handling Sign in, Email Verification, callbacks, etc.

    These are generated automatically with the appropriate sign in options based on the supplied configuration, but you can still create custom authentication pages if you would like to customize the experience.

    More information

    enhancement 
    opened by iaincollins 64
  • Typescript support

    Typescript support

    Summary

    Following the effort @falleco started on #71, this PR aims to bring updated types for v2.

    πŸ—ΊΒ  Roadmap

    • [x] Write types for Server
    • [x] Write types for Server/Providers
    • [x] Write types for Server/Adapters
    • [x] Write types forClient
    • [x] Try to compile types against existing project
    • [ ] Add TS example project
    • [ ] Add TS documentation

    🚨   Disclaimer

    I've been working with TS for a while, but this is my first time typing a library so feel free to comment extensively on what can be improved or might be incorrect. πŸ™πŸ»

    I'm also not familiar with typeorm or the inner workings of both adapters and provider so @iaincollins your guiding light πŸ’‘ here much appreciated 🀞🏻

    enhancement help wanted 
    opened by lluia 52
  • 502: BAD_GATEWAY

    502: BAD_GATEWAY

    502: BAD_GATEWAY While doing GitHub OAuth, i got this.

    An error occurred with this application.
    This is an error with the application itself, not the platform.
    
    502: BAD_GATEWAY
    Code: NO_RESPONSE_FROM_FUNCTION
    ID: bom1::dc4x6-1609474836212-36479d781165
    
    If you are a visitor, contact the website owner or try again later.
    If you are the owner, check the logs for the application error.
    Developer Documentation β†’
    

    Reproduction visit https://bdevg.com/api/auth/signin then choose a sign with Github

    Vercel function logs

    [GET] /api/auth/callback/github?code=248bb9c03e85a89c3070&state=6d154f358c1546618487d1cd81bb4c1686b91a60d135507093fcbbb4930ec29b
    15:20:25:95
    Status:
    -1
    Duration:
    10010.81ms
    Memory Used:
    74 MB
    ID:
    dc4x6-1609474825954-f73eb9e7144f
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
    2021-01-01T04:20:36.092Z 02b5d489-c291-43b5-a9d3-6deff015db6a Task timed out after 10.01 seconds
    [POST] /api/auth/signin/github
    15:20:24:95
    Status:
    302
    Duration:
    82.08ms
    Memory Used:
    66 MB
    ID:
    dc4x6-1609474824954-55d2910131f0
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
    [GET] /api/auth/error?error=oAuthCallback
    15:19:15:43
    Status:
    200
    Duration:
    3.68ms
    Memory Used:
    62 MB
    ID:
    dc4x6-1609474755430-c761c6296b2a
    User Agent:
    Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
    [GET] /api/auth/error?error=oAuthCallback
    15:19:15:07
    Status:
    200
    Duration:
    3.63ms
    Memory Used:
    62 MB
    ID:
    dc4x6-1609474755070-1bd8ee28d530
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41
    [GET] /api/auth/callback/google
    15:19:14:02
    Status:
    302
    Duration:
    5.69ms
    Memory Used:
    62 MB
    ID:
    dc4x6-1609474754021-902653bead5f
    User Agent:
    Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
    2021-01-01T04:19:14.153Z	e1ad9526-d2f5-4a48-8f2c-8c98fd8a7f87	ERROR	[next-auth][error][callback_oauth_error] Error: Invalid state returned from oAuth provider
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:46:27
        at Generator.next (<anonymous>)
        at asyncGeneratorStep (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:26:103)
        at _next (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:194)
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:364
        at new Promise (<anonymous>)
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:97
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:143:17
        at /var/task/bdevg/node_modules/next-auth/dist/server/routes/callback.js:58:31
        at Generator.next (<anonymous>) 
    https://next-auth.js.org/errors#callback_oauth_error
    [GET] /api/auth/error?error=oAuthCallback
    15:19:13:81
    Status:
    200
    Duration:
    3.83ms
    Memory Used:
    62 MB
    ID:
    46tlr-1609474753656-842d690ca3e2
    User Agent:
    Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
    [GET] /api/auth/error?error=oAuthCallback
    15:19:13:44
    Status:
    200
    Duration:
    46.42ms
    Memory Used:
    62 MB
    ID:
    p6rrr-1609474753295-3caf0ab0a8c3
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
    [GET] /api/auth/callback/google
    15:19:12:60
    Status:
    302
    Duration:
    47.13ms
    Memory Used:
    120 MB
    ID:
    p6rrr-1609474752350-528a3121442e
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
    2021-01-01T04:19:12.731Z	f5774683-208d-49fb-b8d7-46a852e6fdda	ERROR	[next-auth][error][callback_oauth_error] Error: Invalid state returned from oAuth provider
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:46:27
        at Generator.next (<anonymous>)
        at asyncGeneratorStep (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:26:103)
        at _next (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:194)
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:364
        at new Promise (<anonymous>)
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:97
        at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:143:17
        at /var/task/bdevg/node_modules/next-auth/dist/server/routes/callback.js:58:31
        at Generator.next (<anonymous>) 
    https://next-auth.js.org/errors#callback_oauth_error
    [POST] /api/auth/signin/google
    15:15:27:33
    Status:
    302
    Duration:
    1440.54ms
    Memory Used:
    119 MB
    ID:
    dc4x6-1609474527333-0021bfe4f74f
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
    Loaded env from .env.production
    [POST] /api/auth/signin/google
    15:15:26:82
    Status:
    302
    Duration:
    1458.67ms
    Memory Used:
    118 MB
    ID:
    dc4x6-1609474526822-bef9b75a6e5c
    User Agent:
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
    Loaded env from .env.production
    
    question stale incomplete 
    opened by ats1999 49
  • Mongo Atlas - MongoServerSelectionError: getaddrinfo ENOTFOUND

    Mongo Atlas - MongoServerSelectionError: getaddrinfo ENOTFOUND

    Your question

    What am I missing using Mongo Atlas?

    What are you trying to do

    1. I'm trying to use Google auth
    2. Whitelisted all IPs on Mongo atlas
    3. Using env variable gives me: [next-auth][error][adapter_connection_error] MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.bixqg.mongodb.net
    4. I tried to do everything from similar issue https://github.com/nextauthjs/next-auth/issues/314 with no success
    5. I tried to deploy to vercel to run it not locally - the same result

    Feedback My code:

    import NextAuth from 'next-auth'
    import Providers from 'next-auth/providers'
    
    const options = {
        // Configure one or more authentication providers
        providers: [
            Providers.Google({
                clientId: process.env.GOOGLE_ID,
                clientSecret: process.env.GOOGLE_SECRET
            }),
        ],
    
        database: process.env.DATABASE_URL,
    };
    
    export default (req, res) => NextAuth(req, res, options)
    

    The full error:

    [next-auth][error][adapter_connection_error] MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.bixqg.mongodb.net
        at Timeout._onTimeout (/Users/maxim/WebstormProjects/tovarisch/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
        at listOnTimeout (internal/timers.js:531:17)
        at processTimers (internal/timers.js:475:7) {
      name: 'MongoServerSelectionError',
      reason: TopologyDescription {
        type: 'Single',
        setName: null,
        maxSetVersion: null,
        maxElectionId: null,
        servers: Map { 'cluster0.bixqg.mongodb.net:27017' => [ServerDescription] },
        stale: false,
        compatible: true,
        compatibilityError: null,
        logicalSessionTimeoutMinutes: null,
        heartbeatFrequencyMS: 10000,
        localThresholdMS: 15,
        commonWireVersion: null
      }
    } 
    
    [next-auth][error][oauth_callback_handler_error] TypeError: Cannot destructure property `manager` of 'undefined' or 'null'.
    
    
    • [x] Found documentation but was incomplete
    question 
    opened by chechenev 41
  • How to resolve [next-auth][warn][jwt_auto_generated_signing_key]

    How to resolve [next-auth][warn][jwt_auto_generated_signing_key]

    Your question How can I resolve the [next-auth][warn][jwt_auto_generated_signing_key] warning?

    I'm using the 3.0.0-beta.22

    What are you trying to do I'm using the credentials provider to try to allow for user/password logins. The login process works fine, but I'm getting this warning in the console.

    I've added the options:

    const options = {
      providers,
      adapter: Adapters.Prisma.Adapter({ prisma }),
      session: {
        jwt: true,
      },
      secret: process.env.SECRET,
      jwt: {
        secret: process.env.JWT_SECRET,
      },
    };
    

    How can I resolve this this warning?

    Documentation feedback The warning generates the link https://next-auth.js.org/warning#jwt_auto_generated_signing_key but this seems to generate an "Page not found" message.

    • [ ] Found the documentation helpful
    • [x] Found documentation but was incomplete
    • [x] Could not find relevant documentation
    • [ ] Found the example project helpful
    • [x] Did not find the example project helpful
    help wanted question documentation 
    opened by jpvanoosten 41
  • Is mutating the session possible?

    Is mutating the session possible?

    Following-up on #325 because I'm not sure if GitHub sends you notifications after an issue has been closed.

    I don't see a way to update data in the session after login. If I'm to store my tokens in the session, I need to be able to write to it after I refresh my access token. I've tried Googling for a solution, but to no avail. Is there something else I'm missing?

    Thanks.

    bug question 
    opened by dkreft 33
  • add(db): Add support for Fauna DB

    add(db): Add support for Fauna DB

    Adds support for FaunaDB as a database adapter.

    I have attempted to mimic the existing adapter implementations, whilst still keeping to the Fauna style where possible. Fauna refs are used to reference related data, although I have opted for storing just the 'id' rather than a ref object. All timestamps are stored as Time objects in UTC (not sure if this will cause any problems down the line?).

    I am not very experienced with Fauna and FQL, so if anyone does have suggestions, I am all ears :-)

    There is some initial setup required by the user to create collections and indexes, although I was not sure if this could be fit into the syncrhonize option somehow.

    CreateCollection({name: 'account'});
    CreateCollection({name: 'session'});
    CreateCollection({name: 'user'});
    CreateCollection({name: 'verification_reset'});
    
    CreateIndex({
        name: 'account_by_provider_account_id',
        source: Collection('account'),
        unie: true,
        terms: [
            { field: ['data', 'providerId'] },
            { field: ['data', 'providerAccountId'] }
        ]
    });
    
    CreateIndex({
        name: 'session_by_token',
        source: Collection('session'),
        unie: true,
        terms: [
            { field: ['data', 'sessionToken'] }
        ]
    });
    
    CreateIndex({
        name: 'user_by_email',
        source: Collection('user'),
        unie: true,
        terms: [
            { field: ['data', 'email'] }
        ]
    });
    
    CreateIndex({
        name: 'verification_reset_by_token',
        source: Collection('verification_reset'),
        unie: true,
        terms: [
            { field: ['data', 'token'] }
        ]
    });
    
    
    released on @canary 
    opened by Joev- 33
  • Documentation Site

    Documentation Site

    Hey so I was thinking, one thing this project is missing is a documentation site.

    I don't know of any nextjs based static documentation generator type projects like docusaurus from facebook or docz with gatsby, but I could whip up a demo docz site which just takes the markdown pages that are already here / in the process of being written for v2, and display them nicely / makes them searchable, etc.

    We could throw it up on now.sh and we'd be good to go.

    Also js.org allows open source projects to grab subdomains for free, so I could get us next-auth.js.org to redirect to our docs page or the repo or whatever you want.

    What do you think @iaincollins ? Might be nice to release a good looking docs page in tandem with v2 soon :)

    help wanted documentation 
    opened by ndom91 31
  • Error: Invalid state returned from Google oAuth provider on production

    Error: Invalid state returned from Google oAuth provider on production

    Hello everyone,

    My Next-Auth application works completely fine when am running this in local environment, the redirection from google, and session registration in MongoDb is working fine,

    When am trying to run the same application with same google id & secret in production, it is throwing Error: Invalid state returned from oAuth provider

    Already SET the valid NEXTAUTH_URL, DATABASE_URL, GOOGLE_ID & GOOGLE_SECRET

    [next-auth][error][callback_oauth_error] Error: Invalid state returned from oAuth provider
        at /home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:46:27
        at Generator.next (<anonymous>)
        at asyncGeneratorStep (/home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:26:103)
        at _next (/home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:194)
        at /home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:364
        at new Promise (<anonymous>)
        at /home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:97
        at /home/node/app/node_modules/next-auth/dist/server/lib/oauth/callback.js:143:17
        at /home/node/app/node_modules/next-auth/dist/server/routes/callback.js:58:31
        at Generator.next (<anonymous>)
    https://next-auth.js.org/errors#callback_oauth_error
    

    Feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

    • [] Found the documentation helpful
    • [X] Found documentation but was incomplete
    • [ ] Could not find relevant documentation
    • [ ] Found the example project helpful
    • [ ] Did not find the example project helpful
    question stale 
    opened by shrmaky 29
  • Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json

    Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json

    Describe the bug

    I keep getting Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json. It's so weird because I see it most of the time but no always. Sometimes I can sign in correctly and sometimes I get redirected to /api/auth/signin?error=Callback# and see this error in the client: Try signing with a different account. This is the full error log:

    [GET] /api/auth/session
    07:12:46:47
    2020-08-06T05:12:46.563Z	044494dc-cf2a-4d4d-899c-a8209f59eec8	ERROR	[next-auth][error][session_error] Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
        at find_package_json_with_name (/var/task/node_modules/require_optional/index.js:56:11)
        at require_optional (/var/task/node_modules/require_optional/index.js:69:13)
        at Object.<anonymous> (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:118:53)
        at Generator.next (<anonymous>)
        at asyncGeneratorStep (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
        at _next (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:30:194)
        at processTicksAndRejections (internal/process/task_queues.js:97:5) 
    https://next-auth.js.org/errors#session_error
    

    To Reproduce My code is in a private repo but if it's necessary I can try to create a new project and replicate it. My code is pretty standard. Just followed the docs. I only have 1 provider (Google) and I've already tried emptying the 3 collections (accounts, users and sessions)

    Documentation feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

    • [X] Found the documentation helpful
    • [ ] Found documentation but was incomplete
    • [ ] Could not find relevant documentation
    • [X] Found the example project helpful
    • [ ] Did not find the example project helpful
    help wanted incomplete 
    opened by matiastucci 29
  • feat(react): preserve history on client-side navigation

    feat(react): preserve history on client-side navigation

    Fixes #2676

    Using window.location.href instead of window.location.reaplace as pointed out by @ndom91 in https://github.com/nextauthjs/next-auth/issues/2676#issuecomment-913875136 will preserve the history.

    core client 
    opened by balazsorban44 2
  • Line Provider Callback got: undefined

    Line Provider Callback got: undefined

    Question πŸ’¬

    When I login from line provider. callback got code and state from line but nextauth error got undefinded image

    image ps. I test in local but I config windows host to virtual domain.

    #environment

    {
      "name": "login",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "dev": "next dev -p 6100",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
      },
      "dependencies": {
        "next": "11.1.2",
        "next-auth": "4.0.0-beta.4",
        "react": "17.0.2",
        "react-dom": "17.0.2"
      },
      "devDependencies": {
        "@types/react": "17.0.27",
        "eslint": "8.0.0",
        "eslint-config-next": "11.1.2",
        "typescript": "4.4.3"
      }
    }
    
    

    How to reproduce β˜•οΈ

    export default NextAuth({
        providers: [
            Google({
                clientId: process.env.GOOGLE_ID,
                clientSecret: process.env.GOOGLE_SECRET,
            }),
            LineProvider({
                clientId: process.env.LINE_CLIENT_ID,
                clientSecret: process.env.LINE_CLIENT_SECRET
            }),
            FacebookProvider({
                clientId: process.env.FACEBOOK_CLIENT_ID,
                clientSecret: process.env.FACEBOOK_CLIENT_SECRET
            })
        ],
        // session: {
        //     jwt: true
        // }
        jwt: {
            secret: "1234"
        },
        pages: {
            signIn: "/signin"
        },
    })
    

    Contributing πŸ™ŒπŸ½

    No, I am afraid I cannot help regarding this

    question 
    opened by shipcake 1
  • feat(providers): add Notion provider

    feat(providers): add Notion provider

    Currently trying to figure out why the owner is not correctly returned.

    https://developers.notion.com/docs/authorization#exchanging-the-grant-for-an-access-token

    Fixes #2905

    Proof after login:

    image

    The image does not show because I got rate-limited with all my failed attempts. πŸ˜…

    providers core 
    opened by balazsorban44 18
  • [V4] Cognito Authentication Errors

    [V4] Cognito Authentication Errors

    Description 🐜

    Hi I'm using version "next-auth": "^4.0.0-beta.4"

        CognitoProvider({
          clientId: `${process.env.COGNITO_CLIENT_ID}`,
          clientSecret: `${process.env.COGNITO_CLIENT_SECRET}`,
          issuer: `${process.env.COGNITO_ISSUER}`,
        }),
    
    

    I'm getting below error.

    [next-auth][error][SIGNIN_OAUTH_ERROR]
    https://next-auth.js.org/errors#signin_oauth_error Cannot read property 'params' of undefined {
      error: {
        message: "Cannot read property 'params' of undefined",
        stack: "TypeError: Cannot read property 'params' of undefined\n" +
          '    at getAuthorizationUrl (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next-auth\\server\\lib\\oauth\\authorization-url.js:25:48)\n' +
          '    at Object.signin (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next-auth\\server\\routes\\signin.js:30:68)\n' +    
          '    at NextAuthHandler (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next-auth\\server\\index.js:202:31)\n' +
          '    at runMicrotasks (<anonymous>)\n' +
          '    at processTicksAndRejections (internal/process/task_queues.js:93:5)\n' +
          '    at async D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next-auth\\server\\index.js:251:32\n' +
          '    at async Object.apiResolver (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next\\dist\\server\\api-utils.js:101:9)\n' +
          '    at async DevServer.handleApiRequest (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next\\dist\\server\\next-server.js:770:9)\n' +
          '    at async Object.fn (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next\\dist\\server\\next-server.js:661:37)\n' +   
          '    at async Router.execute (D:\\Work\\NodeJS\\BDiLabs\\next+mui\\frontend\\node_modules\\next\\dist\\server\\router.js:205:32)',      
        name: 'TypeError'
      },
    
      message: "Cannot read property 'params' of undefined"
    }
    

    Is this a bug in your own project?

    No

    How to reproduce β˜•οΈ

    I'm guessing its coming from here : https://github.com/nextauthjs/next-auth/blob/beta/src/server/lib/oauth/authorization-url.js#L21

        const params = { ...provider.authorization.params,
          ...req.query
        };
    

    When i make it optional provider.authorization?.params it works, but then another issue comes up, session is missing data it used to name like 'name'. This data was there in v3

      profile: {
        id: 'c5ceee18-999-43de-8ea5-d847e6c48b12',
        name: undefined,
        email: '[email protected]',
        image: undefined
      },
    ``
    
    
    ### Screenshots / Logs πŸ“½
    
    I can share cognito credentials if it will help 
    
    ### Environment πŸ–₯
    
      System:
        OS: Windows 10 10.0.19043
        CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
        Memory: 4.36 GB / 15.85 GB
      Binaries:
        Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
        Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
        npm: 7.24.1 - C:\Program Files\nodejs\npm.CMD
      Browsers:
        Chrome: 94.0.4606.71
        Edge: Spartan (44.19041.1023.0), Chromium (93.0.961.44)
        Internet Explorer: 11.0.19041.1202
      npmPackages:
        next: 11.1.3-canary.7 => 11.1.3-canary.7
        next-auth: ^4.0.0-beta.4 => 4.0.0-beta.4
        react: ^17.0.2 => 17.0.2
    
    ### Contributing πŸ™ŒπŸ½
    
    No, I am afraid I cannot help regarding this
    bug 
    opened by DregondRahl 4
  • feat(providers): refactor Apple provider

    feat(providers): refactor Apple provider

    Thanks for helping out with testing this, @sergeymishin

    Fixed apple provider config to support v4.

    #2524

    Proof (🀣...) after signing in: image

    NOTES:

    • no name
    • email only in certain situations
    • no image
    • needs https for local development
    • We removed the option to generate clientSecret on the fly. From now on, you will have to do it in userland like so:
    • Docs need to be updated https://github.com/nextauthjs/docs/blob/main/docs/providers/apple.md
    export default async function auth(req, res) {
      return await NextAuth(req, res, {
        ...
        providers: [
          AppleProvider({
            clientId: process.env.APPLE_ID,
            clientSecret: await generateClientSecret({
              clientId: process.env.APPLE_ID,
              keyId: process.env.APPLE_KEY_ID,
              teamId: process.env.APPLE_TEAM_ID,
              privateKey: process.env.APPLE_PRIVATE_KEY,
            })
          })
        ]
      })
    }
    
    providers core 
    opened by balazsorban44 4
  • refactor: decouple Next.js from core

    refactor: decouple Next.js from core

    Using a similar API to SvelteKit endpoints (https://kit.svelte.dev/docs#routing-endpoints), we can create pure functions without the need of mutating req and res deeply nested in the core of NextAuth.js.

    This will open up new possibilities like expanding to other frameworks #2294 and implement methods like getServerSession #1535

    Thanks to the TypeScript refactoring of the core I did earlier in #2552, I have so much confidence doing this, it might actually make it into v4 after all...

    pages:

    • [x] signin
    • [x] signout
    • [x] error
    • [x] verify-request
    • [x] new-user

    routes:

    • [x] session
    • [x] providers
    • [x] csrf
    • [x] _log
    • [x] signin
    • [x] signout
    • [x] callback

    Also, related: #2612, #2433

    providers core client pages 
    opened by balazsorban44 3
  • feat: rename `callbacks.signIn` to `callbacks.shouldSignIn`

    feat: rename `callbacks.signIn` to `callbacks.shouldSignIn`

    Due to constant misuse of this callback (people use this to mutate the user object, and create stuff in the database, etc. This should be achieved either in the jwt callback or in the appropriate events that we expose instead. The mutation is probably the worse of these two, because that is not something we can guarantee to work in the future.)

    I propose that we change the name to better describe the intended functionality.

    In this PR, I introduced it in a non-breaking manner since I did not want to make new breaking changes in the beta releases, but it is up for debate whether we should just rip off the plaster...

    core 
    opened by balazsorban44 1
  • Strict types

    Strict types

    Reasoning πŸ’‘

    Comply with TS strict typing. Very much WIP.

    Checklist 🧒

    • [X] Documentation - N/A
    • [X] Tests - N/A
    • [X] Ready to be merged - N/A

    Affected issues 🎟

    Partially fixes #2709. TypeScript conversion should be done in a new PR, to keep this PR more concise.

    providers core pages 
    opened by Thisen 4
  • Azure Active Directory XboxLive.signin scope not working

    Azure Active Directory XboxLive.signin scope not working

    Description 🐜

    I used this custom provider and it works but I am getting errors when I add XboxLive.signin scope

    Is this a bug in your own project?

    Yes

    How to reproduce β˜•οΈ

        providers: [
            {
                id: 'azure-ad',
                name: 'Microsoft Account',
                type: 'oauth',
                authorization: {
                    url: `https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?response_mode=query`,
                    params: {
                        scope: 'openid email profile offline_access User.Read', // XboxLive.signin
                    },
                },
                token: `https://login.microsoftonline.com/consumers/oauth2/v2.0/token`,
                userinfo: 'https://graph.microsoft.com/oidc/userinfo',
                clientId: process.env.AZURE_AD_CLIENT_ID,
                clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
                profile(profile) {
                    return {
                        id: profile.sub,
                        name: profile.name,
                        email: profile.email,
                        image: profile.picture,
                    };
                },
            },
        ],
    

    Screenshots / Logs πŸ“½

    https://next-auth.js.org/errors#oauth_callback_error invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.
    Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700
    Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c
    Timestamp: 2021-09-17 14:59:54Z) {
      error: {
        message: "invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.\r\n" +
          'Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700\r\n' +
          'Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c\r\n' +
          'Timestamp: 2021-09-17 14:59:54Z)',
        stack: "OPError: invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.\r\n" +
          'Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700\r\n' +
          'Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c\r\n' +
          'Timestamp: 2021-09-17 14:59:54Z)\n' +
          '    at processResponse (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\node_modules\\openid-client\\lib\\helpers\\process_response.js:45:13)\n' +
          '    at Client.grant (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\node_modules\\openid-client\\lib\\client.js:1237:26)\n' +
          '    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n' +
          '    at async oAuthCallback (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\.next\\server\\pages\\api\\auth\\[...nextauth].js:1692:16)\n' +
          '    at async Object.callback (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\.next\\server\\pages\\api\\auth\\[...nextauth].js:2524:11)\n' +
          '    at async NextAuthHandler (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\.next\\server\\pages\\api\\auth\\[...nextauth].js:794:18)\n' +
          '    at async C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\.next\\server\\pages\\api\\auth\\[...nextauth].js:874:32\n' +
          '    at async Object.apiResolver (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\node_modules\\next\\dist\\server\\api-utils.js:101:9)\n' +
          '    at async DevServer.handleApiRequest (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\node_modules\\next\\dist\\server\\next-server.js:770:9)\n' +
          '    at async Object.fn (C:\\Users\\Nizomidin\\Documents\\GitHub\\lemonjuicer96\\node_modules\\next\\dist\\server\\next-server.js:661:37)',
        name: 'OPError'
      },
      providerId: 'azure-ad',
      message: "invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.\r\n" +
        'Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700\r\n' +
        'Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c\r\n' +
        'Timestamp: 2021-09-17 14:59:54Z)'
    }
    [next-auth][error][CALLBACK_OAUTH_ERROR] 
    https://next-auth.js.org/errors#callback_oauth_error invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.
    Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700
    Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c
    Timestamp: 2021-09-17 14:59:54Z) OPError: invalid_scope (AADSTS70011: The provided request must include a 'scope' input parameter.
    Trace ID: ca99cfc2-61a8-47eb-822a-2e5fa7caa700
    Correlation ID: 7b45c2b3-a6b4-4636-890a-1ec3ed77a61c
    Timestamp: 2021-09-17 14:59:54Z)
        at processResponse (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\node_modules\openid-client\lib\helpers\process_response.js:45:13)
        at Client.grant (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\node_modules\openid-client\lib\client.js:1237:26)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async oAuthCallback (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\.next\server\pages\api\auth\[...nextauth].js:1692:16)
        at async Object.callback (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\.next\server\pages\api\auth\[...nextauth].js:2524:11)
        at async NextAuthHandler (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\.next\server\pages\api\auth\[...nextauth].js:794:18)
        at async C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\.next\server\pages\api\auth\[...nextauth].js:874:32
        at async Object.apiResolver (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\node_modules\next\dist\server\api-utils.js:101:9)
        at async DevServer.handleApiRequest (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\node_modules\next\dist\server\next-server.js:770:9)
        at async Object.fn (C:\Users\Nizomidin\Documents\GitHub\lemonjuicer96\node_modules\next\dist\server\next-server.js:661:37) {
      name: 'OAuthCallbackError'
    }
    

    Environment πŸ–₯

      OS: Windows 10 10.0.19043
      CPU: (4) x64 AMD Ryzen 3 2200G with Radeon Vega Graphics    
      Memory: 1.03 GB / 5.93 GB
    Binaries:
      Node: 16.9.1 - C:\Program Files\nodejs\node.EXE
      Yarn: 1.22.11 - C:\Program Files\nodejs\yarn.CMD
      npm: 7.21.1 - C:\Program Files\nodejs\npm.CMD
    Browsers:
      Edge: Spartan (44.19041.1023.0), Chromium (93.0.961.47)
      Internet Explorer: 11.0.19041.906
    npmPackages:
      next: 11.1.2 => 11.1.2 
      next-auth: 4.0.0-beta.2 => 4.0.0-beta.2 
      react: 17.0.2 => 17.0.2 
    

    Contributing πŸ™ŒπŸ½

    No, I am afraid I cannot help regarding this

    bug 
    opened by LemonJuicer96 0
  • Delete default type for generic param in CredentialsConfig

    Delete default type for generic param in CredentialsConfig

    Reasoning πŸ’‘

    By setting the default type for generic like {} we are blocking the inference of type in credentials as the whole typing is intended to do (I think so).

    After that change we are able to do the following code in TS with strict mode enabled:

    import CredentialsProvider from 'next-auth/providers/credentials';
    
    CredentialsProvider({
      credentials: {
        email: {
          label: 'email',
          type: 'text',
        },
        password: {
          label: 'password',
          type: 'password',
        },
      },
      async authorize() {
        try {
          await fetch('/testing');
    
          return {
            id: '',
          }
        } catch (err) {
          return null;
        }
      },
    }),
    

    I'm aware that marking it as any is never the best solution as I'm doing in the Provider type. But it can get any object shape from us in that case I guess.

    Checklist 🧒

    • [x] Documentation
    • [x] Tests
    • [x] Ready to be merged

    Affected issues 🎟

    Don't know if resolves the following issues so they are just marked as affected.

    #2701 #2677

    providers core 
    opened by kjugi 0
Releases(v4.0.0-beta.4)
  • v4.0.0-beta.4(Oct 3, 2021)

  • v4.0.0-beta.3(Oct 3, 2021)

    4.0.0-beta.3 (2021-10-03)

    Bug Fixes

    • providers: refactor LinkedIn provider (#2821) (1d52600)
    • providers: refactor Okta provider (#2856) (f635035)
    • providers: remove extra brace from jwks_uri (#2813) (04fc3fd)
    • providers: convert to TS, add picture (#2851) (9e1eab0)
    • providers: make string endpoint handlers overrideable (#2842) (b052d4c)
    • providers: refactor Azure AD provider to support v4 (#2818) (424bd04)
    • signin: Set default input type to text to fix CSS (#2881) (0707ba6)
    • login logo height (a177bbb)
    • use default export map syntax for ESM/CJS (#2830) (ffa2b1b)
    • ts: add defaults to OAuthConfig generics (a2c4046)
    • respect id from user options in signinUrl and callbackUrl id (#2698) (819e97e)

    Features

    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-beta.2(Sep 7, 2021)

  • v4.0.0-beta.1(Sep 5, 2021)

    4.0.0-beta.1 (2021-09-05)

    Bug Fixes

    • avoid infinite loop in error handlers (#2647) (245567b)
    • build: use optional-require dependency (#1736) (9fa93e3)
    • callback: respect callbackUrl in Email Provider (#2574) (a9f699f)
    • provider: convert github profile id from int to string (#2108) (ea9b6e3)
    • provider: make userinfo.params optional (#2517) (65040dc)
    • provider: remove double CSS from email template (2c43fbd)
    • react: don't use localStorage on server side (#2166) (abaa5ae)
    • react: initialize session without loading state (#2180) (86ff89e)
    • react: publish react scripts with npm build (#2192) (d10bd9b)
    • ts: add AzureAD to OAuthProviderType (ed34534)
    • ts: allow void return type on delete operations (78d8f28)
    • ts: fix internal react type import (#2450) (92b9d22)
    • use upgraded require optional (#1743) (a6f5f4c)

    Features

    BREAKING CHANGES

    • client: staleTime (previously clientMaxAge) has been removed. Check out refetchInterval instead. It should cover most of the cases. If not, we can look into adding this back later on.
    • provider: By default, the GitHub Provider scope won't ask for full write access to user profiles. If you need that, you will now have to add the user scope to your configuration.
    • prisma-legacy is now gone. Use @next-auth/prisma-adapter. Any features from the old adapter will be migrated over to the new one eventually. This is done so we can require the same default set of options from all the built-in providers, rather than allowing ambiguity on what an official adapter has to support.

    The TypeORM adapter will probably be the only one migrated as-is, but in the future, we would like to break it down to lighter-weight adapters that only support single databases.

    Adapters no longer have to return a getAdapter() method, they can return the actual adapter methods instead. All the values previously being provided through the arguments of getAdapter will now be available in a more digestible format directly in the concerning methods. This behavior was created so that connections could be handled more efficiently. Our review has shown that currently, the TypeORM adapter is the only one that does not handle connections out-of-the-box, so we are going to look into how we can create a wrapper/util function to make it work in the new version. For all other adapters, this will be a huge gain, as with this new API, methods are actually overrideable without creating a whole new custom adapter! πŸ₯³

    Example:

    function MySlightlyCustomAdapter(...args) {
      const adapter = AdapterFromSomeoneElse(...args)
      adapter.someMethodIWantToModify = (...args) => {
        // Much better implementation goes here.
      }
      return adapter
    }
    

    The following method names are changing:

    - getSession
    + getSessionAndUser
    

    This method now requires that you return both the user and the session as {user, session}. If any of these could not be retrieved, you will have to return null instead. (In other words, this must be a transaction.) This requires one less database call, improving the user session retrieval. Any expiry logic included in the Adapter before is now done in the core as well.

    - createVerificationRequest
    + createVerificationToken
    

    Better describes the functionality. This method no longer needs to call provider.sendVerificationRequest, we are moving this into the core. This responsibility shouldn't have fallen to the adapter in the first place.

    createVerificationToken will now receive a VerificationToken object, which looks like this:

    interface VerificationToken {
      identifier: string
      expires: Date
      token: string
    }
    

    The token provided is already hashed, so nothing has to be done, simply write it to your database. (Here we lift up the responsibility from the adapter to hash tokens)

    - getVerificationRequest
    + useVerificationToken
    

    Better describes the functionality. It now also has the responsibility to delete the used-up token from the database. Most ORMs should support retrieving the value while deleting it at the same time, so it will reduce the number of database calls.

    - deleteVerificationRequest
    

    This method is gone. See useVerificationToken.

    Most of the method signatures have been changed, have a look at the TypeScript interface to get a better picture.

    • provider: Providers now have to be imported one-by-one:

    Example:

    - import Provider from "next-auth/providers"
    - Providers.Auth0({...})
    + import Auth0Provider from "next-auth/providers/auth0"
    + Auth0Provider({...})
    
    • events: Two event signatures changed to use named params, signOut and updateUser:
    // [...nextauth].js
    ...
    events: {
    - signOut(tokenOrSession),
    + signOut({ token, session }), // token if using JWT, session if DB persisted sessions.
    - updateUser(user)
    + updateUser({ user })
    }
    
    • logger: The main change is that instead of an unknown number of parameters, the log events have at most two, where the second parameter is usually an object. In the case of the error event, it can also be an Error instance (that is serializable by JSON.stringify). If it is an object, an Error instance will be available on metadata.error, and message will default to metadata.error.message. This is done so that an error event always provides some kind of a stack to see where the error happened
    // [...nextauth.js]
    import log from "some-logger-service"
    ...
    logger: {
    - error(code, ...message) {},
    + error(code, metadata) {},
    - warn(code, ...message) {},
    + warn(code) {}
    - debug(code, ...message) {}
    + debug(code, metadata) {}
    }
    
    • The state option on OAuth providers is now deprecated. Use checks: ["state"] instead. protections is renamed to checks, here is an example:
    - protection: ["pkce"]
    + checks: ["pkece"]
    

    Furthermore, string values are not supported anymore. This is to be able to handle fewer cases internally.

    - checks: "state"
    + checks: ["state"]
    
    • react: The useSession hook now returns an object. Here is how to accommodate for this change:
    - const [ session, loading ] = useSession()
    + const { data: session, status } = useSession()
    + const loading = status === "loading"
    

    With the new status option, you can test states much more clearly.

    • core: The callbacks method signatures are changing the following way:
    - signIn(user, account, profileOrEmailOrCredentials)
    + signIn({ user, account, profile, email, credentials })
    
    - redirect(url, baseUrl)
    + redirect({ url, baseUrl })
    
    - session(session, tokenOrUser)
    + session({ session, token, user })
    
    - jwt(token, user, account, OAuthProfile, isNewUser)
    + jwt({ token, user, account, profile, isNewUser })
    

    NOTE: You only need to define the params that you actually need (no more need for _ params.)

    This way, if you only need token and account in the jwt callback, you can write:

    jwt({ token, account }) {
      if(account) {
        token.accessToken = account.access_token
      }
      return token
    }
    
    • The lowest supported Node version isΒ 12. (We still support IE11 in browsers, until that is not dropped by Next.js itself)

    react:

    1. next-auth/client is renamed to next-auth/react.

    2. In the past, we exposed most of the functions with different names for convenience. To simplify our source code, the new React specific client code exports only the following functions, listed with the necessary changes:

    • setOptions: Not exposed anymore, use SessionProvider props
    • options: Not exposed anymore, use SessionProvider props
    • session: Rename to getSession
    • providers: Rename to getProviders
    • csrfToken: Rename to getCsrfToken
    • signin: Rename to signIn
    • signout: Rename to signOut
    • Provider: Rename to SessionProvider

    3. Provider changes.

    • Provider is renamed to SessionProvider
    • The options prop is now flattened as the props of SessionProvider.
    • keepAlive has been renamed to refetchInterval. An example of the changes:
    - <Provider options={{clientMaxAge: 0, keepAlive: 0}}>{children}</Provider>
    + <SessionProvider refetchInterval={0}>{children}</SessionProvider> 
    

    4. It is now required to wrap the part of your application that uses useSession into a SessionProvider.

    Usually, the best place for this is in your pages/_app.jsx file:

    import { SessionProvider } from "next-auth/react"
    
    export default function App({
      Component,
      pageProps: { session, ...pageProps }
    }) {
      return (
        // `session` comes from `getServerSideProps` or `getInitialProps`.
        // Avoids flickering/session loading on first load.
        <SessionProvider session={session}>
          <Component {...pageProps} />
        </SessionProvider>
      )
    }
    
    • provider: If you currently use AzureADB2C, you will need to update it to to AzureAD There should be no other changes needed.
    • adapter: From now on, you will have to import your own adapter

    Check out https://github.com/nextauthjs/adapters

    The migration is super easy and has HUGE advantages for those not using TypeORM.

    // [...nextauth].js
    + import TypeORMAdapter from "@next-auth/typeorm-legacy-adapter"
    import NextAuth from "next-auth"
    
    ...
    export default NextAuth({
    -  database: "yourconnectionstring",
    + adapter: TypeORMAdapter("yourconnectionstring")
    })
    

    Co-authored-by: Lluis Agusti [email protected] Co-authored-by: Giovanni Carnel [email protected]

    • build: typeorm, and nodemailer are no longer dependencies added by default. If you need any of them, you will have to install them yourself in your project directory. TypeOrm is the default adapter, so if you only provide an adapter configuration or a database, you will need typeorm. You could also check out @next-auth/typeorm-adapter. In case you are using the Email provider, you will have to install nodemailer (or you can use the choice of your library in the sendVerificationRequest callback to send out the e-mail.)
    • provider: adding state: true is already redundant as protection: "state is the default value. state: false can be substituted with protection: "state"
    • We have supported throwing strings for redirections, while we were showing a waring. From now on, it is not possible. The user MUST return a string, rather than throw it.
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-next.26(Sep 2, 2021)

  • v4.0.0-next.25(Aug 29, 2021)

    4.0.0-next.25 (2021-08-29)

    Features

    BREAKING CHANGES

    • client: staleTime (previously clientMaxAge) has been removed. Check out refetchInterval instead. It should cover most of the cases. If not, we can look into adding this back later on.
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-next.24(Aug 23, 2021)

    4.0.0-next.24 (2021-08-23)

    Bug Fixes

    • callback: respect callbackUrl in Email Provider (#2574) (a9f699f)
    • provider: remove double CSS from email template (2c43fbd)

    Features

    • provider: add Keycloak provider (#2485) (eb8ba69)
    • provider: use more restrictive default scope for GitHub (#2579) (e15bf9b)

    BREAKING CHANGES

    • provider: By default, the GitHub Provider scope won't ask for full write access to user profiles. If you need that, you will now have to add the user scope to your configuration.
    Source code(tar.gz)
    Source code(zip)
  • v3.29.0(Aug 23, 2021)

  • v4.0.0-next.23(Aug 16, 2021)

  • v4.0.0-next.22(Aug 15, 2021)

    4.0.0-next.22 (2021-08-15)

    Bug Fixes

    Features

    BREAKING CHANGES

    • prisma-legacy is now gone. Use @next-auth/prisma-adapter. Any features from the old adapter will be migrated over to the new one eventually. This is done so we can require the same default set of options from all the built-in providers, rather than allowing ambiguity on what an official adapter has to support.

    The TypeORM adapter will probably be the only one migrated as-is, but in the future, we would like to break it down to lighter-weight adapters that only support single databases.

    Adapters no longer have to return a getAdapter() method, they can return the actual adapter methods instead. All the values previously being provided through the arguments of getAdapter will now be available in a more digestible format directly in the concerning methods. This behavior was created so that connections could be handled more efficiently. Our review has shown that currently, the TypeORM adapter is the only one that does not handle connections out-of-the-box, so we are going to look into how we can create a wrapper/util function to make it work in the new version. For all other adapters, this will be a huge gain, as with this new API, methods are actually overrideable without creating a whole new custom adapter! πŸ₯³

    Example:

    function MySlightlyCustomAdapter(...args) {
      const adapter = AdapterFromSomeoneElse(...args)
      adapter.someMethodIWantToModify = (...args) => {
        // Much better implementation goes here.
      }
      return adapter
    }
    

    The following method names are changing:

    - getSession
    + getSessionAndUser
    

    This method now requires that you return both the user and the session as {user, session}. If any of these could not be retrieved, you will have to return null instead. (In other words, this must be a transaction.) This requires one less database call, improving the user session retrieval. Any expiry logic included in the Adapter before is now done in the core as well.

    - createVerificationRequest
    + createVerificationToken
    

    Better describes the functionality. This method no longer needs to call provider.sendVerificationRequest, we are moving this into the core. This responsibility shouldn't have fallen to the adapter in the first place.

    createVerificationToken will now receive a VerificationToken object, which looks like this:

    interface VerificationToken {
      identifier: string
      expires: Date
      token: string
    }
    

    The token provided is already hashed, so nothing has to be done, simply write it to your database. (Here we lift up the responsibility from the adapter to hash tokens)

    - getVerificationRequest
    + useVerificationToken
    

    Better describes the functionality. It now also has the responsibility to delete the used-up token from the database. Most ORMs should support retrieving the value while deleting it at the same time, so it will reduce the number of database calls.

    - deleteVerificationRequest
    

    This method is gone. See useVerificationToken.

    Most of the method signatures have been changed, have a look at the TypeScript interface to get a better picture.

    • provider: Providers now have to be imported one-by-one:

    Example:

    - import Provider from "next-auth/providers"
    - Providers.Auth0({...})
    + import Auth0Provider from "next-auth/providers/auth0"
    + Auth0Provider({...})
    
    Source code(tar.gz)
    Source code(zip)
  • v3.28.0(Aug 12, 2021)

  • v4.0.0-next.21(Aug 12, 2021)

  • v4.0.0-next.20(Aug 4, 2021)

    4.0.0-next.20 (2021-08-04)

    Features

    BREAKING CHANGES

    • events: Two event signatures changed to use named params, signOut and updateUser:
    // [...nextauth].js
    ...
    events: {
    - signOut(tokenOrSession),
    + signOut({ token, session }), // token if using JWT, session if DB persisted sessions.
    - updateUser(user)
    + updateUser({ user })
    }
    
    • providers: Basecamp provider is removed. See the explanation here

    ALL OAuth providers' profile callback is expected to only return these fields by default from now on: id, name, email, and image at most. Any of these missing values should be set to null.

    The following new options are available:

    1. authorization (replaces authorizationUrl, authorizationParams, scope)
    2. token replaces (accessTokenUrl, headers, params)
    3. userinfo (replaces profileUrl)

    These three options map nicely to the OAuth spec's three endpoints for

    1. initiating the login flow
    2. retrieve OAuth tokens
    3. retrieve user information

    They all take the form of EndpointHandler:

    type EndpointRequest<C, R> = (
      context: C & {
        /** `openid-client` Client */
        client: Client
        /** Provider is passed for convenience, ans also contains the `callbackUrl`. */
        provider: OAuthConfig & {
          signinUrl: string
          callbackUrl: string
        }
      }
    ) => Awaitable<R>
    
    /** Gives granular control of the request to the given endpoint */
    type AdvancedEndpointHandler<P extends UrlParams, C, R> = {
      /** Endpoint URL. Can contain parameters. Optionally, you can use `params`*/
      url?: string
      /** These will be prepended to the `url` */
      params?: P
      /**
       * Control the corresponding OAuth endpoint request completely.
       * Useful if your provider relies on some custom behavior
       * or it diverges from the OAuth spec.
       *
       * - warning **This is an advanced option.**
       * You should **try to avoid using advanced options** unless you are very comfortable using them.
       */
      request?: EndpointRequest<C, R>
    }
    
    /** Either an URL (containing all the parameters) or an object with more granular control. */
    type EndpointHandler<P extends UrlParams, C = any, R = any> =
      | string
      | AdvancedEndpointHandler<P, C, R>
    

    In case of authorization, the EndpointHandler can define the params as AuthorizationParameters

    Note: authorization does not implement request yet. We will have to see if there is demand for it.

    From now on, instead of using the ... spread operator when adding a new built-in provider, the user is expected to add options as a property at the end of the default config. This way, we can deep merge the user config with the default one. This is needed to let the user do something like this:

    MyProvider({
      clientId: "",
      clientSecret: "",
      authorization: { params: {scope: ""} }
    })
    

    So even if the default config defines anything in authorization, only the user-defined parts will be overridden.

    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-next.19(Jul 11, 2021)

    4.0.0-next.19 (2021-07-11)

    Features

    BREAKING CHANGES

    • logger: The main change is that instead of an unknown number of parameters, the log events have at most two, where the second parameter is usually an object. In the case of the error event, it can also be an Error instance (that is serializable by JSON.stringify). If it is an object, an Error instance will be available on metadata.error, and message will default to metadata.error.message. This is done so that an error event always provides some kind of a stack to see where the error happened
    // [...nextauth.js]
    import log from "some-logger-service"
    ...
    logger: {
    - error(code, ...message) {},
    + error(code, metadata) {},
    - warn(code, ...message) {},
    + warn(code) {}
    - debug(code, ...message) {}
    + debug(code, metadata) {}
    }
    
    • The state option on OAuth providers is now deprecated. Use checks: ["state"] instead. protections is renamed to checks, here is an example:
    - protection: ["pkce"]
    + checks: ["pkece"]
    

    Furthermore, string values are not supported anymore. This is to be able to handle fewer cases internally.

    - checks: "state"
    + checks: ["state"]
    
    Source code(tar.gz)
    Source code(zip)
  • v3.27.3(Jul 8, 2021)

  • v3.27.2(Jul 5, 2021)

  • v4.0.0-next.18(Jul 5, 2021)

    4.0.0-next.18 (2021-07-05)

    Features

    • react: make session requireable in useSession (#2236) (a2e5afa)

    BREAKING CHANGES

    • react: The useSession hook now returns an object. Here is how to accommodate for this change:
    - const [ session, loading ] = useSession()
    + const { data: session, status } = useSession()
    + const loading = status === "loading"
    

    With the new status option, you can test states much more clearly.

    Source code(tar.gz)
    Source code(zip)
  • v3.27.1(Jun 27, 2021)

  • v4.0.0-next.17(Jun 26, 2021)

    4.0.0-next.17 (2021-06-26)

    Features

    BREAKING CHANGES

    • core: The callbacks method signatures are changing the following way:
    - signIn(user, account, profileOrEmailOrCredentials)
    + signIn({ user, account, profile, email, credentials })
    
    - redirect(url, baseUrl)
    + redirect({ url, baseUrl })
    
    - session(session, tokenOrUser)
    + session({ session, token, user })
    
    - jwt(token, user, account, OAuthProfile, isNewUser)
    + jwt({ token, user, account, profile, isNewUser })
    

    NOTE: You only need to define the params that you actually need (no more need for _ params.)

    This way, if you only need token and account in the jwt callback, you can write:

    jwt({ token, account }) {
      if(account) {
        token.accessToken = account.access_token
      }
      return token
    }
    
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-next.16(Jun 26, 2021)

  • v3.27.0(Jun 15, 2021)

  • v4.0.0-next.15(Jun 15, 2021)

  • v4.0.0-next.14(Jun 14, 2021)

  • v4.0.0-next.13(Jun 11, 2021)

  • v4.0.0-next.12(Jun 11, 2021)

    4.0.0-next.12 (2021-06-11)

    Features

    BREAKING CHANGES

    1. next-auth/client is renamed to next-auth/react.

    2. In the past, we exposed most of the functions with different names for convenience. To simplify our source code, the new React specific client code exports only the following functions, listed with the necessary changes:

    • setOptions: Not exposed anymore, use SessionProvider props
    • options: Not exposed anymore, use SessionProvider props
    • session: Rename to getSession
    • providers: Rename to getProviders
    • csrfToken: Rename to getCsrfToken
    • signin: Rename to signIn
    • signout: Rename to signOut
    • Provider: Rename to SessionProvider

    3. Provider changes.

    • Provider is renamed to SessionProvider
    • The options prop is now flattened as the props of SessionProvider.
    • clientMaxAge has been renamed to staleTime.
    • keepAlive has been renamed to refetchInterval. An example of the changes:
    - <Provider options={{clientMaxAge: 0, keepAlive: 0}}>{children}</Provider>
    + <SessionProvider staleTime={0} refetchInterval={0}>{children}</SessionProvider> 
    

    4. It is now required to wrap the part of your application that uses useSession into a SessionProvider.

    Usually, the best place for this is in your pages/_app.jsx file:

    import { SessionProvider } from "next-auth/react"
    
    export default function App({
      Component,
      pageProps: { session, ...pageProps }
    }) {
      return (
        // `session` comes from `getServerSideProps` or `getInitialProps`.
        // Avoids flickering/session loading on first load.
        <SessionProvider session={session}>
          <Component {...pageProps} />
        </SessionProvider>
      )
    }
    
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0-next.11(Jun 10, 2021)

  • v4.0.0-next.10(Jun 10, 2021)

  • v3.26.1(Jun 9, 2021)

  • v3.26.0(Jun 9, 2021)

  • v4.0.0-next.9(Jun 9, 2021)

Owner
NextAuth.js
Authentication for Next.js
NextAuth.js
Zero config PWA plugin for Next.js, with workbox 🧰

Zero Config PWA Plugin for Next.js This plugin is powered by workbox and other good stuff. Features 0️⃣ Zero config for registering and generating a s

Wei Wang 1.7k Oct 15, 2021
πŸ›  Next.js stateless session utility using signed and encrypted cookies to store data

next-iron-session ?? Next.js and Express (connect middleware) stateless session utility using signed and encrypted cookies to store data This Next.js,

Vincent Voyer 938 Oct 18, 2021
Authentication for Next.js

NextAuth.js Authentication for Next.js Open Source. Full Stack. Own Your Data. Overview NextAuth.js is a complete open source authentication solution

NextAuth.js 7.7k Oct 15, 2021
Next.js plugin to transpile code from node_modules

Next.js + Transpile node_modules Transpile modules from node_modules using the Next.js Babel configuration. Makes it easy to have local libraries and

Pierre de la Martinière 734 Oct 14, 2021
The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2

next-connect The smol method routing and middleware for Next.js (also works in other frameworks). Powered by trouter. Features Compatible with Express

Hoang 782 Oct 16, 2021
The easiest way to translate your NextJs apps.

next-i18next The easiest way to translate your NextJs apps. If you are using next-i18next in production, please consider sponsoring the package with a

Isaac Hinman 2.6k Oct 14, 2021
Simple promise-based session middleware for Next.js, micro, Express, and more

next-session Simple promise-based session middleware for Next.js. Also works in micro or Node.js HTTP Server, Express, and more. Project status: While

Hoang 201 Oct 10, 2021
Effortless deployment to AWS and GitHub Pages for Next.js apps πŸš€

Next Deploy Effortless deployment to AWS and GitHub Pages for Next.js apps ?? Table of Contents Getting Started Features Background CLI Distributed De

Egor Philippov 39 Sep 16, 2021
Easily add a blog to any next.js based project.

next-mdx-blog Easy blog for next.js next-mdx-blog enables you to easily add a blog to any next.js based project. EXAMPLE: http://hipstersmoothie.com/b

Andrew Lisowski 64 Oct 19, 2021
nextjs + purgecss for smaller css bundles

next-purgecss Next.js + Purgecss = ?? Next.js makes it easy to create SSR and static React applications. Purgecss helps you remove unused CSS. Install

Luc Leray 129 Oct 7, 2021
Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing

Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing

Paco 1.2k Oct 14, 2021
A Next.js plugin for embedding optimized images.

Next.js plugin for embedding optimized images. Features import png/jpg images output to webp format resize to multiple screen sizes and densities opti

Humaans 180 Oct 3, 2021
A simple and light-weight SEO plugin for Next.js applications.

next-head-seo A simple and light-weight SEO plugin for Next.js applications. ⚑️ < 1kb gzipped ✨ Zero dependencies ✍️ Designed based on Google Webmaste

catnose 106 Oct 18, 2021
Universal Lambda Routing

Next Routes Middleware Universal Lambda Routing for Next.JS application Roadmap for 4.0.0 Integrate with existing now.json in now.config.js for better

Truong Hoang Dung 40 Sep 10, 2021
Enable Fast Refresh for remote data in NextJS.

Enable Fast Refresh for remote data in NextJS.

Travis Arnold 32 Sep 9, 2021
Universal dynamic routes for Next.js

Dynamic Routes for Next.js Easy to use universal dynamic routes for Next.js Express-style route and parameters matching Request handler middleware for

null 2.3k Oct 16, 2021
Extended Next.js server with pkg support

Next-Pkg is a package for compiling your Next.js project with pkg. This is how you can deploy your Next.js apps on enviroments without node installed!

Federico Miras 55 Aug 30, 2021
Validate NEXT.js API Routes with joi

next-joi Validate NEXT.js API Routes with joi ?? Install Getting started How does it work? Working with NEXT.js API Routes NEXT.js & connect-like midd

Codecoolture 61 Oct 6, 2021
next-useragent parses browser user-agent strings for next.js

next-useragent ⚠️ Version 2 of this library will work only with Next.js 9. If you're using Next.js 6-8 you can use previous versions. ⚠️ next-useragen

Tsuyoshi Tokuda 258 Oct 12, 2021