question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

šŸ“¢ NextAuth.js 2.0 Announcement

See original GitHub issue

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 next-auth@canary 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

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:27
  • Comments:64 (49 by maintainers)

github_iconTop GitHub Comments

5reactions
aol-nnovcommented, May 26, 2020

Update for Monday, 26 May 2020

Get some sleep, @iaincollins , it’s Tuesday already 🤣

Awesome job, anyway! Thank you!!

5reactions
LoriKarikaricommented, May 14, 2020

Might be a good idea to make a core package with just the library which you can add to your app with custom UI. And create a separate package with pre-built UIs which are optional?

Read more comments on GitHub >

github_iconTop Results From Across the Web

NextAuth.js
NextAuth.js is becoming Auth.js! šŸŽ‰ We're creating Authentication for the Web. Everyone included. You are looking at the NextAuth.js (v4) documentation.
Read more >
nextauth session type | The AI Search Engine You Control
NextAuth.js has its own type definitions to use in your TypeScript projects safely. ... nextauthjs/next-authšŸ“¢ NextAuth.js 2.0 Announcement #99.
Read more >
next-auth - npm
NextAuth.js. Authentication for Next.js. Open Source. Full Stack. Own Your Data. Release Bundle Size Downloads Github Stars Github StableĀ ...
Read more >
Announcing SvelteKit Auth: Bringing NextAuth.js to all ... - Vercel
SvelteKit Auth is a simple, low configuration authentication library for SvelteKit applications, with support for many popular OAuthĀ ...
Read more >
Authentication for Next.js - BestofReactjs
iaincollins/next-auth, NextAuth.js Authentication for Next.js Open Source. Full Stack. Own Your Data. ... šŸ“¢ NextAuth.js 2.0 Announcement ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found