Next JS Authentication setup using Auth0 || its easy

Next JS Authentication setup using Auth0 || its easy

auth0

what is auth0

Auth0 provides authentication and authorization as a service. We are here to give developers and companies the building blocks they need to secure their applications without having to become security experts. You can connect any application (written in any language or on any stack) to Auth0 and define the identity providers you want to use (how you want your users to log in). Based on your app’s technology, choose one of our SDKs (or call our API), and hook it up to your app. Now each time a user tries to authenticate, Auth0 will verify their identity and send the required information back to your app.

Auth0 Central Components ForwardAuth is built on the following central components from Auth0:

  • Authorization Code OAuth 2.0 grant-flow Applications
  • APIs
  • Role Based Access Control
  • Users, Roles and Permissions
  • Rules

Lets use this auth0 with our nextjs application to provide authentication

Installation

CREATE NEXT.JS APP To create a brand new Next.js app, we will use create-next-app, which sets up everything automatically for you. To create the project, run:

npx create-next-app [name-of-the-app]
Or
yarn create next-app [name-of-the-app]

To start the develop server locally and see the site just created in your browser, go to the new folder that you created:

cd [name-of-the-app]
#And run:
npm run dev
#Or
yarn dev
npm install @auth0/nextjs-auth0

This library supports the following tooling versions:

  • Node.js: ^10.13.0 || >=12.0.0
  • Next.js: >=10

Getting Started

Auth0 Configuration

Create a Regular Web Application in the Auth0 Dashboard.

If you're using an existing application, verify that you have configured the following settings in your Regular Web Application:

  • Click on the "Settings" tab of your application's page.
  • Scroll down and click on the "Show Advanced Settings" link.
  • Under "Advanced Settings", click on the "OAuth" tab.
  • Ensure that "JsonWebToken Signature Algorithm" is set to RS256 and that "OIDC Conformant" is enabled.

Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: http://localhost:3000/api/auth/callback
  • Allowed Logout URLs: http://localhost:3000/

Take note of the Client ID, Client Secret, and Domain values under the "Basic Information" section. You'll need these values in the next step.

Basic Setup

Configure the Application

You need to allow your Next.js application to communicate properly with Auth0. You can do so by creating a .env.local file under your root project directory that defines the necessary Auth0 configuration values as follows:

# A long, secret value used to encrypt the session cookie
AUTH0_SECRET='LONG_RANDOM_VALUE'
# The base url of your application
AUTH0_BASE_URL='http://localhost:3000'
# The url of your Auth0 tenant domain
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
# Your Auth0 application's Client ID
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
# Your Auth0 application's Client Secret
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'

You can execute the following command to generate a suitable string for the AUTH0_SECRET value:

node -e "console.log(crypto.randomBytes(32).toString('hex'))"

You can see a full list of Auth0 configuration options in the "Configuration properties" section of the "Module config" document.

For more details about loading environmental variables in Next.js, visit the "Environment Variables" document.

Add the Dynamic API Route

Go to your Next.js application and create a catch-all, dynamic API route handler under the /pages/api directory:

  • Create an auth directory under the /pages/api/ directory.
  • Create a [...auth0].js file under the newly created auth directory.

The path to your dynamic API route file would be /pages/api/auth/[...auth0].js. Populate that file as follows:

import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

Executing handleAuth() creates the following route handlers under the hood that perform different parts of the authentication flow:

  • /api/auth/login: Your Next.js application redirects users to your Identity Provider for them to log in (you can optionally pass a returnTo parameter to return to a custom relative URL after login, eg /api/auth/login?returnTo=/profile).
  • /api/auth/callback: Your Identity Provider redirects users to this route after they successfully log in.
  • /api/auth/logout: Your Next.js application logs out the user.
  • /api/auth/me: You can fetch user profile information in JSON format.

Add the UserProvider to Custom App

Wrap your pages/_app.js component with the UserProvider component:

To handle user authentication state on the frontend of our web application we can use UserProvider React component, available on Auth0 Next.js SDK. the component uses React Context internally.

If you want to access the user authentication state on a Component, you should wrap it with a UserProvider component.

<UserProvider>
  <Component {...props} />
</UserProvider>

If we want to access all of the pages in our application, we should add the component to the pages/app.js file. pages/app.js overrides the React App component. It’s a feature that Next.js exposes to customize our application. You can read more about it here.

import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}
// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

Consume Authentication

You can now determine if a user is authenticated by checking that the user object returned by the useUser() hook is defined. You can also log in or log out your users from the frontend layer of your Next.js application by redirecting them to the appropriate automatically-generated route:

All these routes gets created just by placing pages/api/auth/[...auth0].js this file with provided code and then our application can do linking with lofin/signup routes

  • /api/auth/login
  • /api/auth/signup
  • /api/auth/logout
  • /api/auth/callback
  • /api/auth/me
// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';

export default function Index() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  if (user) {
    return (
      <div>
        Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
      </div>
    );
  }

  return <a href="/api/auth/login">Login</a>;
}

Next linting rules might suggest using the Link component instead of an anchor tag. The Link component is meant to perform client-side transitions between pages. As the links point to an API route and not to a page, you should keep them as anchor tags.

There are two additional ways to check for an authenticated user; one for Next.js pages using withPageAuthRequired and one for Next.js API routes using withAPIAuthRequired.

For other comprehensive examples, see the EXAMPLES.md document.

Documentation

API Reference

Server-side methods:

The user object contains information related to the user’s identity. If the person visiting the page is not logged in (we don’t have a user object available), we will display a link to the login page. If the user is already authenticated, we will display user.name and user.email properties on the page, and a Logout link.

Let’s create a videos.js file, with a list of three YouTube video URLs that will only be visible for registered people. To only allow logged users to see this page, we will use withPageAuthRequired method from the SDK.

import { withPageAuthRequired } from "@auth0/nextjs-auth0";

export default () => {
 return (
   <div>
     <a href="https://www.youtube.com/watch?v=5qap5aO4i9A">LoFi Music</a>
     <a href="https://www.youtube.com/watch?v=fEvM-OUbaKs">Jazz Music</a>
     <a href="https://www.youtube.com/watch?v=XULUBg_ZcAU">Piano Music</a>
   </div>
 );
};

export const getServerSideProps = withPageAuthRequired();

Comments