Adding authentication to Next.js with Auth0
Daniel Afonso —
Photo by Amol Tyagi on Unsplash
Setting authentication in Next.js apps can be stressing and confusing. To make your life easier, Auth0 created an SDK that makes this process simpler and fast.
In this blog post, I’ll show you how to add authentication to your Next.js application using the Auth0 SDK, how to display the authenticated user information, how to authenticate with a social provider and protecting a route.
Setup
Auth0 dashboard
So the first thing you need is an Auth0 account. You can sign up for free at https://auth0.com/signup.
Once you have your account setup, on the application settings dashboard create a new application with the Regular Web Applications type.
Create a Regular Web ApplicationNow that you have your application, you will need to get some data and do some configurations first, here’s what you need to do:
- Copy your Domain value (we’ll use it in the next step)
- Copy your Client ID value (we’ll use it in the next step)
- Copy your Client Secret value (we’ll use it in the next step)
- Add
http://localhost:3000/api/auth/callback
to the Allowed Callback URLs so that it can call back to it after logging in - Add
http://localhost:3000/
to the Allowed Logout URLs so that it can redirect to it after logging out
Now we configured everything on the dashboard, the next thing you will need is an application.
Next.js Application
On this project you should do two things first:
1. Install auth0/nextjs-auth0 SDK
npm install @auth0/nextjs-auth0
Install Auth0 Next.js SDK
2. Add your previously copied domain, client id and secret to your .env.local
file
AUTH0_SECRET='LONG_RANDOM_VALUE'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL=<Add your domain here>
AUTH0_CLIENT_ID=<Add your client id here>
AUTH0_CLIENT_SECRET=<Add your client secret here>
Add Domain Id, Client Id and Client Secret to .env.local file
3. Create a Dynamic API route handler
On the pages/api
folder create an auth
directory. In this auth
folder, now create a file named [...auth0].js
. This file will be responsible for generating the login, callback, logout and me endpoints to be used by the api.
In this folder add the following snippet.
import { handleAuth } from "@auth0/nextjs-auth0";
export default handleAuth();
Add dynamic api route handler
4. Wrap your _app.js component with the UserProvider
In our pages/_app.js
we need to import the UserProvider
component from the Next.js sdk and wrap our component with it.
import React from "react";
import { UserProvider } from "@auth0/nextjs-auth0";
export default function App({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
Wrapping Component with UserProvider
On this snippet, we wrap our App component with the UserProvider
which is a context provider that stores the authentication state of our users and allows for children of this component to access it.
Having our component wrapped with the UserProvider
, now we can start using the useUser
hook.
Login
For adding the ability to login to your application, you can make use of the /api/auth/login
route.
const Login = () => {
return <a href="/api/auth/login">Login</a>;
};
Using login route
Here we show our Login
component. In this component, we make use of the login route to redirect the user to the log in dashboard.
Logout
For adding the ability to log out to your application, you can make use the /api/auth/logout
route
const Logout = () => {
return <a href="/api/auth/logout">Logout</a>;
};
Using logout inside route
Here we show our Logout
component. In this component, we make use of the logout route to log the user out.
Authentication State: useUser
useUser
is a custom React hook that’s part of the Auth0 Next.js SDK. This hook provides you with authentication details like the user data, errors and loading state.
import { useUser } from "@auth0/nextjs-auth0";
const Profile = () => {
const { user, error, isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
if (user) {
return (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
</div>
);
}
};
Using useUser custom hook to display authenticated user information
Protecting a route
By using the withPageAuthRequired
function from the SDK we can pass that function call to the getServerSideProps
function. Doing so all requests to that page without a valid session cookie will be redirected to the login page.
import { withPageAuthRequired } from "@auth0/nextjs-auth0";
export default function Profile({ user }) {
return <div>Hello {user.name}</div>;
}
export const getServerSideProps = withPageAuthRequired();
Protecting a route
Bonus: Adding new social authentication within the Auth0 portal
By default on the Auth0 Universal Login page, you’ll only be able to use Google as a Social Identity Provider. In this section, I’ll show you how Auth0 makes it easy for you to add a new social provider to your application.
Step 1
On the application settings dashboard go to the social connections tab to see all the currently configured social connections you have. Click on the Create Connection button. (Click here to skip this and the previous step).
Social Connections PageStep 2
Select one provider. In this example, I’ll be choosing GitHub (Click here to skip this and the previous steps).
Select one providerStep 3
Scroll down and click on the Create button.
Add Github as a social providerStep 4
You now can toggle this provider for your application.
Add GitHub as a social provider to your applicationStep 5
Try to log in on your application again.
GitHub now shows up as an authentication optionTLDR
Just in case you want a quick summary of everything here it is:
- Create an Auth0 account at https://auth0.com/signup
- Get the Domain, Client ID and Client Secret from your application at https://manage.auth0.com/#/applications and add them to your application .env.local
- Configure your Allowed Callback URLs, in this case, add
http://localhost:3000/api/auth/callback
- Configure your Allowed Logout URLs, in this case, add
http://localhost:3000
- Install Auth0 Next.js SDK
- Add dynamic api route handler
- Wrap your main component with the UserProvider.
- Use the
/api/auth/login
route to redirect to the login page - Use the
/api/auth/logout
route to log the user out - With the
useUser
hook, destructure the user variable to access authentication state inside a component - To protect a route add the
withPageAuthRequired
function call to thegetServerSideProps
function.
Hope everyone enjoyed and stay tuned!