NextAuth
NextAuth is an authenticaton library for Next.js projects.
It contains an example site that shows how to use it in a simple project.
It's also used in the nextjs-starter.now.sh project, which provides a more complete example.
Example usage
If you have an existing site you can add authentication to it by creating an index.js
file in the root of your project containing the following:
// Include Next.js, Next Auth and a Next Auth configconst next = const nextAuth = const nextAuthConfig = // Load environment variables from .env // Initialize Next.jsconst nextApp = // Add next-auth to next appnextApp
The easist way to get started to to copy the following configuration files into the root of your project:
You can copy over the pages from the example project into your own pages directory and customise them:
You may want to add the following to your package.json
file to start the project:
"scripts": ,
You can add a .env
file to the root of the project as a place to specify configuration options:
SERVER_URL=http://localhost:3000
MONGO_URI=mongodb://localhost:27017/my-database
FACEBOOK_ID=
FACEBOOK_SECRET=
GOOGLE_ID=
GOOGLE_SECRET=
TWITTER_KEY=
TWITTER_SECRET=
EMAIL_FROM=username@gmail.com
EMAIL_SERVER=smtp.gmail.com
EMAIL_PORT=465
EMAIL_USERNAME=username@gmail.com
EMAIL_PASSWORD=
Configuration
NextAuth configuration can be split into into three files, which makes it easier to manage.
You can copy these from the included example project to get started.
next-auth.config.js
Basic configuration is defined in next-auth.config.js
It also where next-auth.functions.js and next-auth.providers.js are loaded.
next-auth.functions.js
CRUD methods for user management and sending email are defined in next-auth.functions.js
- find({id,email,emailToken,provider}) // Get user
- insert(user) // Create user
- update(user) // Update user
- remove(id) // Remove user
- serialize(user) // Get ID from user
- deserialize(id) // Get user from ID
- sendSigninEmail({email, url}) // Send email
The example configuration is designed to work with Mongo DB, but by defining the behaviour in these functions you can use NextAuth with any database, including a relational database that uses SQL.
next-auth.providers.js
Configuration for oAuth providers are defined in next-auth.functions.js
The example configuration file supports Facebook, Google and Twitter but can be updated to support any oAuth provider.
See AUTHENTICATION.md for a guide on how to set up oAuth providers.
See the nextjs-starter.now.sh project for working example of how to use NextAuth and live demo.