Next.js 15 Authentication with NextAuth and Upstash Redis
Published: Jul 17, 2023
Updated: Oct 24, 2024
Authentication plays a crucial role in modern applications. And for Next.js developers, NextAuth.js is a go to solution. It seamlessly integrates with Next.js and when paired with Upstash Redis, a serverless Redis database service, it boosts both speed and security. This combination helps create efficient and optimized authentication for Next.js applications. In this post, we’ll look at how to set up authentication in Next.js using NextAuth.js and Upstash Redis.
Warning: Before moving forward, make sure you have installed Node.js (version ≥ 18) on your machine.
Setup Next.js App
Let’s create a Next.js app with App directory by using the following command:
Now, our basic Next.js app has been created. Let’s add some necessary packages:
Create Auth Service
Create lib/auth.ts
file in the same level of app
folder and paste the following code:
Here, we are using UpstashRedisAdapter
to connect our NextAuth with Upstash Redis and GitHub
as our authentication provider.
Create Auth route
Now, create api/auth/[...nextauth]/route.ts
file inside the app
folder. Paste the following code:
With this, we have implemented Auth route for our app.
Setup Env Variables
Now, We need to create .env
file at the root of our app with the following:
To get Github Provider credentials, go to https://github.com/settings/developers and create a new Oauth App like this:
after registering your app, you will get the Client ID and can generate the Client Secret by clicking on the generate new client secret
button.
To get Upstash credentials, go to Upstash and create a new account if you don’t have any. Then create a new Redis database. now, go below and you will see a block named “REST API”, click on the .env
tab and copy the values.
One last thing, you need to add AUTH_SECRET
in your .env
file which you can add by running npx auth secret
command.
That’s it. Now, we can start working on our ui part.
Create Auth Page
Now, Let’s create signin and signout button to authenticate our users. Replace everything in the app/page.tsx
file with the following:
- Here we are getting the session using
auth
and check if session is valid or not. - Then, if session is invalid, then show
Sign In
button. - If session is valid, then show
User
andSign Out
button.
Now, start dev server using npm run dev
and visit http://localhost:3000 to see the preview.
If you have followed all the steps carefully, now your app should work perfectly.
Wrap Up
Check out the preview here. The code is available on GitHub.
If you face any trouble, please let me know on Twitter