Authentication for Next.js

This week I released NextAuth, a module specifically designed for Next.js and React, that supports email sign in and oAuth.

It comes with example configuration for Facebook, Google+, Twitter and email sign in and uses Mongo DB to store accounts, but it is easy to extend to work with other providers and other databases.

It has a client for React called NextAuthClient which is an isomorphic (client and server side) library that populates session state in pages.

Populating session state in a React with NextAuth


The NextAuth library uses Express and Passport to provide support for signing in with email and with services like Facebook, Google and Twitter.

NextAuth adds Cross Site Request Forgery (CSRF) tokens and HTTP Only cookies, supports univeral rendering and does not require client side JavaScript.

It adds session support without using client side accessible session tokens, providing protection against Cross Site Scripting (XSS) and session hijacking, while leveraging localStorage where available to cache non-critical session state for optimal performance in Single Page Apps.


NextAuth includes it’s own minimal example project but the NextJS Starter Project provides a more complete example.

The code for NextAuth is based on code originally used in the NextJS Starter Project, which now uses NextAuth and NextAuthClient.


While the documentation is comprehensive and there are multiple examples of how to use it, it’s still far more cumbersome to add authentication to sites that it needs to be.

In future, I’d like to simplify the interface further so it can be configured just by setting ID & SECRET values for each oAuth provider and a database URI, while still allowing for more advanced custom configuration.


If you haven’t seen Next.js yet and are at all intersted in React I you should really check it out.

It’s a really wonderful and unopinioned way to sites with React without having to configure bable, webpack, routing or server side rendering.

Like what you read? Give Iain Collins a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.