How To Implement Authentication In Subsequent.js With Auth0

No Comments

“Authentication” is the motion of validating {that a} person is who she or he claims to be. We normally do that by implementing a credentials system, like person/password, safety questions, and even facial recognition.

“Authorization” determines what a person can (or can’t) do. If we have to deal with authentication and authorization in our net utility, we’ll want a safety platform or module. We are able to develop our personal platform, implement it, and keep it. Or we will take the benefit of current authentication and authorization platforms out there which might be supplied as providers.

When evaluating whether or not it’s higher for us to create our personal platform, or to make use of a third-party service, there are some issues that we must always take into account:

Designing and creating authentication providers is just not our core talent. There are folks working specifically targeted on safety subjects that may create higher and safer platforms than us;
We are able to save time counting on an current authentication platform and spend it including worth to the services and products that we care about;
We don’t retailer delicate data in our databases. We separate it from all the info concerned in our apps;
The instruments third-party providers supply have improved usability and efficiency, which makes it simpler for us to administrate the customers of our utility.

Contemplating these elements, we will say that counting on third-party authentication platforms might be simpler, cheaper, and much more safe than creating our personal safety module.

On this article, we’ll see the best way to implement authentication and authorization in our Subsequent.js functions utilizing one of many current merchandise out there: Auth0.

What Is Auth0?

It lets you add safety to apps developed utilizing any programming language or know-how.

“Auth0 is a versatile, drop-in answer so as to add authentication and authorization providers to your functions.”

Dan Arias,

Auth0 has a number of attention-grabbing options, comparable to:

Single Signal-On: When you log into an utility that makes use of Auth0, you received’t need to enter your credentials once more when coming into one other one which additionally makes use of it. You’ll be mechanically logged in to all of them;
Social login: Authenticate utilizing your most well-liked social community profile;
Multi-Issue Authentication;
A number of customary protocols are allowed, comparable to OpenID Join, JSON Net Token, or OAuth 2.0;
Reporting and analytics instruments.

There’s a free plan that you should use to begin securing your net functions, protecting as much as 7000 month-to-month energetic customers. You’ll begin paying when the quantity of customers will increase.

One other cool factor about Auth0 is that we’ve got a Subsequent.js SDK obtainable to make use of in our app. With this library, created particularly for Subsequent.js, we will simply connect with the Auth0 API.

Auth0 SDK For Subsequent.js

As we talked about earlier than, Auth0 created (and maintains) a Subsequent.js targeted SDK, amongst different SDKs obtainable to connect with the API utilizing numerous programming languages. We simply must obtain the NPM bundle, configure some particulars about our Auth0 account and connection, and we’re good to go.

This SDK offers us instruments to implement authentication and authorization with each client-side and server-side strategies, utilizing API Routes on the backend and React Context with React Hooks on the frontend.

Let’s see how a few of them work in an instance Subsequent.js utility.

Instance Subsequent.js App Utilizing Auth0

Let’s return to our earlier video platform instance, and create a small app to indicate the best way to use Auth0 Subsequent.js SDK. We’ll arrange Auth0’s Common Login. We can have some YouTube video URLs. They are going to be hidden beneath an authentication platform. Solely registered customers will be capable of see the checklist of movies by our net utility.

Word: This text focuses on the configuration and use of Auth0 in your Subsequent.js utility. We received’t get into particulars like CSS styling or database utilization. If you wish to see the whole code of the instance app, you possibly can go to this GitHub repository.

Create Auth0 Account And Configure App Particulars

Initially, we have to create an Auth0 account utilizing the Signal Up web page.

After that, let’s go to the Auth0 Dashboard. Go to Purposes and create a brand new app of sort [“Regular Web Applications”].

Now let’s go to the Settings tab of the applying and, beneath the Utility URIs part, configure the next particulars and save the adjustments:

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

By doing this, we’re configuring the URL the place we wish to redirect the customers after they login our web site (Callback), and the URL the place we redirect the customers after they log off (Logout). We should always add the manufacturing URLs after we deploy the ultimate model of our app to the internet hosting server.

Auth0 Dashboard has many configurations and customizations we will apply to our tasks. We are able to change the kind of authentication we use, the login/sign-up web page, the info we request for the customers, allow/disable new registrations, configure customers’ databases, and so forth.

Create Subsequent.js App

To create a model new Subsequent.js app, we’ll use create-next-app, which units up every part mechanically for you. To create the venture, run:

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


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

To start out the develop server regionally and see the location simply created in your browser, go to the brand new folder that you simply created:

cd [name-of-the-app]

And run:

npm run dev


yarn dev

Set up And Configure The Auth0 Subsequent.js SDK

Let’s set up the Auth0 Subsequent.js SDK in our app:

npm set up @auth0/nextjs-auth0


yarn add @auth0/nextjs-auth0

Now, in our env.native file (or the atmosphere variables menu of our internet hosting platform), let’s add these variables:

AUTH0_SECRET=”[A 32 characters secret used to encrypt the cookies]”
AUTH0_ISSUER_BASE_URL=”https://[Your tenant domain. Can be found in the Auth0 dashboard under settings]”
AUTH0_CLIENT_ID=”[Can be found in the Auth0 dashboard under settings]”
AUTH0_CLIENT_SECRET=”[Can be found in the Auth0 dashboard under settings]”

If you’d like extra configuration choices, you possibly can check out the docs.

Create the Dynamic API Route

Subsequent.js affords a solution to create serverless APIs: API Routes. With this characteristic, we will create code that will probably be executed in each person request to our routes. We are able to outline mounted routes, like /api/index.js. However we will even have dynamic API routes, with params that we will use in our API routes code, like /api/weblog/[postId].js.

Let’s create the file /pages/api/auth/[…auth0].js, which will probably be a dynamic API route. Inside the file, let’s import the handleAuth technique from the Auth0 SDK, and export the outcome:

import { handleAuth } from ‘@auth0/nextjs-auth0’;

export default handleAuth();

This can create and deal with the next routes:

To carry out login or enroll with Auth0.
To log the person out.
To redirect the person after a profitable login.
To get the person profile data.

And that may be the server-side a part of our app. If we wish to log in to our utility or join a brand new account, we must always go to http://localhost:3000/api/auth/login. We should always add a hyperlink to that route in our app. Identical for logging out from our web site: Add a hyperlink to http://localhost:3000/api/auth/logout.

Add The UserProvider Part

To deal with person authentication state on the frontend of our net utility we will use UserProvider React element, obtainable on Auth0 Subsequent.js SDK. the element makes use of React Context internally.

If you wish to entry the person authentication state on a Part, it’s best to wrap it with a UserProvider element.

<Part {…props} />

If we wish to entry the entire pages in our utility, we must always add the element to the pages/_app.js file. pages/_app.js overrides the React App element. It’s a characteristic that Subsequent.js exposes to customise our utility. You’ll be able to learn extra about it right here.

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

export default operate App({ Part, pageProps }) {
return (
<Part {…pageProps} />

Now we have a React hook useUser that accesses to the authentication state uncovered by UserProvider. We are able to use it, as an example, to create a sort of welcome web page. Let’s change the code of the pages/index.js file:

import { useUser } from “@auth0/nextjs-auth0″;

export default () => {
const { person, error, isLoading } = useUser();

if (isLoading) return <div>Loading…</div>;

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

if (person) {
return (
<p>{person.electronic mail}</p>
<a href=”/api/auth/logout”>Logout</a>
return <a href=”/api/auth/login”>Login</a>;

The person object accommodates data associated to the person’s id. If the particular person visiting the web page is just not logged in (we don’t have a person object obtainable), we’ll show a hyperlink to the login web page. If the person is already authenticated, we’ll show person.identify and person.electronic mail properties on the web page, and a Logout hyperlink.

Let’s create a movies.js file, with an inventory of three YouTube video URLs that can solely be seen for registered folks. To solely permit logged customers to see this web page, we’ll use withPageAuthRequired technique from the SDK.

import { withPageAuthRequired } from “@auth0/nextjs-auth0″;

export default () => {
return (
<a href=””>LoFi Music</a>
<a href=””>Jazz Music</a>
<a href=””>Piano Music</a>

export const getServerSideProps = withPageAuthRequired();

Take into accounts that our net utility permits any particular person to join an account, utilizing the Auth0 platform. The person can even re-use an current Auth0 account, as we’re implementing Common Login.

We are able to create our personal registration web page to request extra particulars in regards to the person or add fee data to invoice them month-to-month for our service. We are able to additionally use the strategies uncovered within the SDK to deal with authorization in an computerized method.


On this article, we noticed the best way to safe our Subsequent.js functions utilizing Auth0, an authentication and authorization platform. We consider the advantages of utilizing a third-party service for the authentication of our net functions in comparison with creating our personal safety platform. We created an instance Subsequent.js app and we secured it utilizing Auth0 free plan and Auth0 Subsequent.js SDK.

If you wish to deploy an Auth0 instance utility to Vercel, you are able to do it right here.

Additional Studying And Sources

Auth0 Subsequent.js SDK GitHub repository, Auth0, GitHub
The Final Information To Subsequent.js Authentication With Auth0,” Sandrino Di Mattia, Auth0 Weblog
In our instance app, we used server-side rendering, with API routes and a serverless method. If you happen to’re utilizing Subsequent.js for a static web site, or a customized server to host your app, this text has some particulars about the best way to implement authentication.
New Common Login Expertise,” Auth0 Common Login, Auth0 Docs
Centralized Common Login vs. Embedded Login,” Auth0 Common Login, Auth0 Docs

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment