BLOG

Basic GitHub OAuth Authentication with Next.js and next-auth

A step-by-step infographic showing the process to set up authentication with Next.js using the next-auth library.

Pablo Haller

Engineering Lead

Oct 15, 2024

Next.js

Tools

Tips

Ever wondered how to easily set-up authentication with Next.js?

One of my favorite libraries for handling problem is next-auth, a library created to handle many authorization providers. It facilitates single sign-on with services like Google, Discord, and GitHub.

Let me show you a simple way to authenticate using GitHub with just a few steps.

Set Up the GitHub OAuth App

Open your browser, and go to GitHub’s Register a new OAuth Application form.

For now, feel free to add some placeholder information, but make sure to set your callback URL to:

http://localhost:3000/api/auth/callback/github

A screenshot of GitHub’s "Register a new OAuth Application" form. The form contains fields for application name, homepage URL, and the callback URL, which is set to http://localhost:3000/api/auth/callback/github. There are placeholder values entered in the other fields.

Then click on Register application, and your brand new app will be created!

Generating your client secret

You’ll be redirected to the app settings page. Once there, click on Generate a new client secret and wait until it displays below to copy it.

A screenshot of the GitHub app settings page, showing the "Generate a new client secret" button. Below the button, the newly generated client secret is displayed in a masked format with a copy button next to it.

Once you’ve copied it, paste it into an .env file in the root of your application, alongside the Client ID.

Remember to create an .env.example for your future self to know what environment variables you need, or for anyone who wants modify your code. This will let them know what they need ahead of time.

Also, make sure to add the .env file to your .gitignore file. This will ensure that you won’t expose sensitive information or keys.

You’ll end up having something like this:

A screenshot of a text editor showing an .env file. The file includes two lines: GITHUB_ID=your_client_id and GITHUB_SECRET=your_client_secret.
.env.example file

Adding next-auth

Run npm i next-auth to install the library.

Then, since we’re using the app router, we'll also need to use route handlers for the config. Create the following route:

Screenshot of a terminal window showing the command npm i next-auth being run to install the next-auth library. Below that, a code editor displays the creation of a route handler in the file path /app/api/auth/[...nextauth]/route.ts. The code initializes NextAuth with configuration options, including GitHub authentication using clientId and clientSecret from the environment variables.
Route handler for authentication under /app/api/auth/[…nextauth]/route.ts

What does this do?

It generates our auth options, an object that declares which providers we’re using (e.g.: GitHub, Google, Twitch; you can find the full list here). As you can see, we need to specify the clientId and clientSecret, which we previously stored in our .env file.

We will also need to create a secret, and store it in our environment variables. This will be used to encrypt your JSON Web Token: an encoded field with useful information used for authentication and authorization purposes.

For the session property, we specify the jwt strategy and set the maxAge for the token. This is the maximum amount of time the application will allow us to be logged in before ending our session. I recommend setting this to 60 to help us see how next-auth automatically signs us out once the session expires. Feel free to change this according to your needs!

Protecting our routes

The whole purpose of authentication is protecting our resources, in this case, our routes.

Let’s create a middleware, a function that handles pre-processing for all routes.

A screenshot of a text editor showing a middleware file (middleware.ts). The code uses the next-auth/middleware and defines a configuration object with a matcher property, specifying protected routes like /dashboard.
middleware.ts and next-auth/middleware

The above example is one of the basic ways to do it, though there are many others.

We run the next-auth middleware (next-auth/middleware) in the Next.js middleware (middleware.ts file). Through the config object and its matcher property, we tell exactly which routes to run it.

You can read a brief explanation of how Next.js middleware works here, and here to learn how next-auth one works.

Creating the route

We’re almost there!

Let’s create a page for our dashboard.

A screenshot of the code for the dashboard page. The code includes the getServerSession function to fetch the session data, and it displays the logged-in GitHub user’s name and email on the page.
app/dashboard/page.tsx showing our information

As you can see, it’s a typical Next.js page, using getServerSession to print our session information on the page. Nothing more, nothing less. It will also provide us with our GitHub user name, e-mail, and profile picture URL for later use as basic information.

Testing GitHub OAuth Authentication

Now, we can finally test our authentication process. After you run the project, try accessing /dashboard.

You will be prompted with the following screen, provided by next-auth itself:

A screenshot of the login screen provided by next-auth. The page shows a GitHub button prompting the user to sign in using their GitHub account. This is the authentication prompt that appears when trying to access the /dashboard route.

Once you click on it, you will be asked to grant permission from your GitHub account.

Image showing GitHub’s permission request page. The user is asked to grant the newly registered OAuth application permission to access their GitHub account details. A blue "Authorize" button is visible at the bottom of the screen.

Once you authorize it, you’ll be redirected and finally see our information!

A screenshot showing the writers’s profile picture at the top, followed by their name in bold text, and below that, their email address.

If you wait long enough (a minute), the application will log you out, returning you to the same log-in screen as before.

A great question to ask here is, how can I sign out without having to wait for the token to expire?

Simply calling signOut from a client component is good enough, which is detailed here.

Conclusion

next-auth simplifies the process of implementing authentication in Next.js applications, making it easier to integrate with popular OAuth providers like GitHub. With just a few steps, you can set up secure authentication, protect routes, and manage sessions effortlessly.

If you would like to check out the code used for this blog post, you can find it here.

Pablo Haller

Engineering Lead

Oct 15, 2024

Next.js

Tools

Tips

BLOG

Unlock forbidden knowledge

Explore more

Arrow Icon
Efficiently Caching Translations in React with Zustand and Google Translate API

Frontend

Guides

Efficiently Caching Translations in React with Zustand and Google Translate API

Learn to integrate Zustand and Google Translate API for a seamless translation feature. Cache results to reduce API calls, boost performance, and enhance scalability.

Mauro Davoli

Fast API Development with Hono and Cloudflare Workers

Backend

Technology

Guides

Fast API Development with Hono and Cloudflare Workers

Pablo shares his journey of finding tools to build REST APIs quickly and efficiently. He highlights his experience with Hono, a lightweight framework reminiscent of Express, designed specifically for Cloudflare Workers.

Pablo Haller

Building cool search UIs with Algolia and InstantSearch

Frontend

Technology

Guides

Building cool search UIs with Algolia and InstantSearch

In this article, we’re going to pick some characters from a video game (Genshin Impact) and display them in a fancy way using the aforementioned programs.

Pablo Haller