How to Set Up User Login Authentication in Next.js with Auth0: 6 Easy Steps
Hello everyone, I hope you're doing great. In this post, we're going to discuss how to set up user login authentication using Auth0 in Next.js projects in five steps.
Step 1: Create Your Aouth0 Account
First , head to Aouth0 and create your Aouth0 account .
On the dashboard, select Applications, then click on Create Application. Give a name to your application and select it Regular Web Application
then click Create.
Select settings, then scroll down to Application URIs. Inside that, fill the ALLOWED_CALLBACK_URL
and the ALLOWED_LOGOUT_URL
like showed in the image below then click save changes.
Step 2: Setting up Next.js app and installing dependencies
Lets now create our application, We are going to use tailwind css to style it up a little bit.
On the command prompt, run the following command to set up the application:
npx create-next-app@latest
Make sure to set the application as shown below
Once it has finished creating, navigate to the application using the following command and install @auth0/nextjs-auth0
package
cd auth0-app
npm install @auth0/nextjs-auth0
Step 3: Creating .env.local
file to store credentials
Create a .env.local file in the root directory and paste the following in the file. make sure to change AUTH0_CLIENT_ID
, AUTH0_CLIENT_SECRET
and AUTH0_ISSUER_BASE_URL
with values of your Auth0, which are on the dashboard. on the ISSUER_BASE_URL
make sure https://
is present.
AUTH0_SECRET='LONG_RANDOM_VALUE_32_CHARACTERS_LONG'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth.com'
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'
To get AUTH0_SECRET
run the following command to generate the 32 characters string
node -e "console.log(crypto.randomBytes(32).toString('hex'))"_
Step 4: Creating API Routes
In step four, we'll create API routes for login, logout, and callback, which is really straightforward.
first Navigate to the pages
directory and create the api/auth
directory or run the following command on the terminal.
mkdir -p app/api/auth
In the auth create a file and name it in square bracket like this [...auth0].js .
Paste the code below in the [...auth0] file.
import {handleAuth} from "@auth0/nextjs-auth0";
export default handleAuth();
Step 5: Wrap the application with userProvider
Paste the following code in the _app.js
file.
import "../styles/globals.css";
import { UserProvider } from "@auth0/nextjs-auth0";
function MyApp({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
export default MyApp;
The MyApp
component wraps the entire application in the UserProvider
, ensuring that the authentication state is available throughout the app. It then renders the specific page component (Component
) with its associated props (pageProps
).
Run the application on the terminal using this command npm run dev
and navigate to localhost:3000/api/auth/loginto see the Auth0 Login page and you will be able to use it and sign in to it.
Step 6: Creating Components
In this section, let's create our component to be displayed when we run our application. In the root directory of the project, start by creating a folder called components
.
In the components folder, create the files Button.js
and Header.js
. Then, paste the following code into each file, respectively.
//Header.js
import Link from "next/link";
import Button from "./Button";
const Header = ({ userLoggedIn }) => {
return (
<header className="h-[90px] shadow-md shadow-indigo-500 bg-slate-900">
<div className="container px-4 sm:px-6 py-4 flex justify-between items-center">
{/* Logo */}
<Logo />
<div className="flex px-5 py-2 justify-between items-center">
{!userLoggedIn ? (
<Button type="Sign In" url="/api/auth/login" />
) : (
<div className="flex justify-center items-center space-x-4">
<Link href="/members-only">
<a className="text-2xl font-semibold text-indigo-200 mx-3">Members Only</a>
</Link>
<Button type="Logout" url="/api/auth/logout" />
</div>
)}
</div>
</div>
</header>
);
};
export default Header;
//Button.js
import Link from "next/link";
const Button = ({type ,url}) => {
return (
<Link href={url}>
<a className={`btn ${type === 'Sign In' ? 'bg-orange-500 hover:bg-orange-600 text-white' : 'bg-orange-300 hover:bg-orange-400 text-orange-700'}`}>
{type}
</a>
</Link>
)
}
export default Button
We use Auth0 to show pages in our websites which can only be seen if the user is authenticated. If a person is not logged in, we can display a Sign In button; if he is logged in, we can display a Logout button.
To implement this, we need to use the custom hook useUser
provided by the Auth0 package.
Navigate to page/index.js
and paste the following code:
import Head from "next/head";
import Header from "../components/Header";
import { useUser } from "@auth0/nextjs-auth0";
export default function Home() {
const { user, error, isLoading } = useUser();
// you can use the error and loading state to show an error message or a loading spinner while loading.
if (isLoading) {
return (
<div className="text-5xl font-semibold text-center text-indigo-600">
...loading{" "}
</div>
);
}
if(error){
return (
<div className="text-5xl font-semibold text-center text-indigo-600">
{error.message}
</div>
)
}
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Header userLoggedIn={user} />
<h1 className="text-4xl mt-6 font-bold text-indigo-500 text-center">
Welcome to the Nextjs-Auth0 Demo Application.
</h1>
<div className="max-w-[500px] border-4 border-indigo-400 rounded-lg p-6 mx-auto text-3xl mt-16 font-bold text-indigo-700 text-center">
{user && (
<p className="mb-6">
Welcome <span className="text-amber-600">{user.name}</span>
</p>
)}
{!user && (
<p>You are Not signed In, Please Sign In to view the Secret Pages.</p>
)}
</div>
</div>
);
}
Assume you have a members-only page in your application, and you want only authenticated users to access it.
The nextjs-auth0 SDK includes the withPageAuthRequired
Hook, which makes this simple.
To implement this, create a members-only.js file in the pages folder and paste the below code in it.
import {withPageAuthRequired } from "@auth0/nextjs-auth0";
const membersOnly = () => {
return (
<div>
<h1 className="text-5xl font-semibold mt-10 text-center text-indigo-600">Your a member now.</h1>
</div>
)
}
export default membersOnly
export const getServerSideProps = withPageAuthRequired();
As a result, only authenticated users can see the website, while those who are not authenticated will be served a 404 page or instantly forwarded to the login page.
Conclusion
So that was it about configuring user login authentication in Next.js with Auth0. I hope you found this guide useful and enjoyed making the project. If you found this useful, please check my original blog for more extensive information. Don't forget to follow me on Twitter for updates and join me on LinkedIn to stay connected.