Archived course lesson
Add Auth0 library
Objective: Add the and configure Auth0 library for future login and logout api functions.
We will be using Auth0 Hooks for this section and we are working off a guide that Auth0 created about integrating Next.js with Auth0. The first step is to add the @auth0/nextjs-auth0 package:
npm install --save @auth0/nextjs-auth0
Next, we need to create private variables that we will load into the Next.js server. Add the entire serverRuntimeConfig block to the next.config.js file:
require('dotenv').config();
const {
BRANCH,
GRAPHCMSURL,
GRAPHCMSPROJECTID,
domain,
clientId,
clientSecret,
scope,
redirectUri,
postLogoutRedirectUri,
cookieSecret,
} = process.env;
module.exports = {
publicRuntimeConfig: {
graphcms: {
BRANCH,
GRAPHCMSURL,
GRAPHCMSPROJECTID,
},
},
serverRuntimeConfig: {
auth: {
domain,
clientId,
clientSecret,
scope,
redirectUri,
postLogoutRedirectUri,
},
cookieSecret,
},
};
These secrets will only be available via functions that we create in the pages/api folder. A cool new veature in Next.js 9 is that any functions which are created in the api folder will be available as functions that your frontend can call against your actively running server. This means a function set as the export default in pages/api/me.js will appear at www.mydomain.com/api/me after we deploy our site. To make it even more convenient, if we deploy our app serverlessly, the me function will actually be converted to a lambda function and we can access it in the same way.
Let’s start by using the initAuth0 method to create an instance of the Auth0 plugin.
import { initAuth0 } from '@auth0/nextjs-auth0';
import getConfig from 'next/config';
const { serverRuntimeConfig } = getConfig();
const { auth, cookieSecret } = serverRuntimeConfig;
export default initAuth0({
...auth,
session: {
cookieSecret,
cookieLifetime: 60 * 60 * 8,
storeIdToken: false,
storeAccessToken: false,
storeRefreshToken: false,
},
oidcClient: {
httpTimeout: 2500,
clockTolerance: 10000,
},
});