Authentication & Authorization for Next.js
next-authentication
provides a set of functions and middlewares to implement Authentication, Authorization and session management in Next.js applications.
Setup:
// Setup
// file: lib/auth.js
import bcrypt from 'bcrypt';
import { nextAuth, AuthError } from 'next-authentication';
import { User } from '../user/model';
const nextAuthOptions = {
cookieName: 'auth-token',
// Pseudo code that verifies a user in a fictitious database
verify: async (username, password) => {
try {
const user = await User.query().findOne({ username });
if (!user) {
throw new AuthError('User does not exist', 404);
}
const valid = bcrypt.compareSync(password, user.password);
if (!valid) {
throw new AuthError('Invalid credentials', 403);
}
return { user: user.username }
} catch (error) {
throw new AuthError(`Error trying to verifying the user: ${error.message}`, 500);
}
},
secret: process.env.SECRET || 'alongsecretvaluethatsatleast16chars'
}
export const { authenticate, authorize } = nextAuth(nextAuthOptions);
Login:
// Authenticate
// file: pages/api/login.js
import { authenticate } from '../lib/auth.js'
const handler = (req, res) => {
res.status(200).json({ message: 'User logged in', user: req.user });
}
export default authenticate(handler);
Restricted content:
// Authorize
// file: pages/api/restricted-content.js
import { authorize } from '../lib/auth.js';
const handler = (req, res) => {
console.log('is authorized', res.isAuthorized);
res.status(200).json({ user: res.user })
}
export default authorize(handler);
A requestListener
function that is executed each time an API route gets a request.
This is not a next-authentication
method, but rather a definition about a parameter we use through the documentation. It’s handy to have the definition for reference.
req
<IncomingMessage>res
<ServerResponse>
Usage:
// file: pages/api/ok.js
const handler = (req, res) => {
res.end(JSON.stringify({ message: 'ok' }));
}
export default handler;
The main function of the library that takes an option object and returns an object with the functions you to use for authentication, authorization, and logout users.
username
<string> (required)password
<string> (required)- Returns an object with at least a
username
element. e.g.,{ username: 'jolvera' }
A function that takes a username and a password and must return an object containing at least the key username
. The function should run the logic to verify the authenticity of a user's identity.
- Default:
false
- Default: "next-authentication-token"
A secret string that’s at least 16 characters long.
- Default:
{ httpOnly: true, maxAge: 60 * 60 * 24, path: "/" }
Same options as cookie.serialize
.
- Default:
true
If true
, next-authentication
redirects the user to redirectUrl
when:
- The user provides invalid credentials
- The user logs out
- There is an unknown error
- Default:
/login
URL to redirect the user to if redirectOnError
is true
.
A function middleware that verifies the user and creates a cookie session.
You can use the function directly, but the recommended way is through nextAuth
since the options are setup once there and can be use everywhere. If you use the function directly you will have to call the function with all parameters every time you use it.
Validates a session.
Destroys the user session and redirects the user based on redirectOnError
and redirectUrl
.
Custom error class for Authorization errors.
Error message to use in a response <ServerResponse> object.
- Default:
401
Server status code to use in a response <ServerResponse> object.
With npm:
$ npm i next-authentication --save