github nextauthjs/next-auth v4.0.0-beta.1

latest releases: next-auth@5.0.0-beta.18, @auth/azure-tables-adapter@1.1.0, @auth/d1-adapter@1.1.0...
pre-release2 years ago

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 hi@llu.lu
Co-authored-by: Giovanni Carnel 479046+g10@users.noreply.github.com

  • 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.

Don't miss a new next-auth release

NewReleases is sending notifications on new releases.