Next.js Protected API Routes (with NextAuth)
Next.js is a popular React framework that allows you to build server-side rendered and static websites. NextAuth is an authentication library for Next.js that provides easy and secure authentication and authorization for your applications.
One of the features that Next.js and NextAuth provide is the ability to create protected API routes. This allows you to create API endpoints that require authentication to access, ensuring that only authorized users can make requests to these routes.
Setting up NextAuth
To get started with NextAuth, you first need to install it in your Next.js application. You can do this by running the following command in your terminal:
npm install next-auth
Once NextAuth is installed, you will need to configure it with your authentication provider, such as Google, GitHub, or your own custom provider. NextAuth provides easy-to-use configuration options that allow you to set up authentication with just a few lines of code.
Creating a Protected API Route
After setting up NextAuth, you can create a protected API route in your Next.js application. To do this, you simply need to create a new file in the pages/api directory and use the getSession function from NextAuth to check if the user is authenticated.
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
if (session) {
// If the user is authenticated, handle the request
res.status(200).json({ message: 'This is a protected route' })
} else {
// If the user is not authenticated, return a 401 Unauthorized status
res.status(401).json({ message: 'Unauthorized' })
}
}
In this example, we use the getSession function to check if the user has an active session. If the user is authenticated, we return a 200 status with the data. If the user is not authenticated, we return a 401 status, indicating that the user is unauthorized to access the route.
Securing Your API Routes
With NextAuth, you can easily secure your Next.js API routes and ensure that only authorized users can access them. By using the getSession function, you can check if the user is authenticated and handle the request accordingly.
Next.js protected API routes with NextAuth provide a simple and secure way to create authenticated endpoints for your application. By following the steps outlined in this article, you can set up protected API routes in your Next.js application and ensure that only authorized users can access them.
You explained so well and simply that I didn't understand why it wasn't working for me, but I needed to realize that I used another way. I'm currently using Next.js 14 and Node.js 20, with JavaScript and NextAuth, using credential providers and JWT, and not using Google OAuth or another provider. Also, I used MongoDB as the database and created the user model with Mongoose. The configuration in this case is a little tricky.
In Next.js 14, the _app.js file is 'replaced' with layout.js', and it is recommended to use NextAuthProviderfor the{children}` in this specific file.
In this case, I needed to use the getToken helper imported from next-auth/jwt. It just receives exactly a 'req' and the secret that is in the .env.local file. For example, getToken({ req, secret }).
For more details, and maybe if anyone is struggling with this issue, I will provide the link to the NextAuth docs: https://next-auth.js.org/tutorials/securing-pages-and-api-routes
Hi, thanks for the video!
I believe getServerSession is now stable
–> import { getServerSession } from 'next-auth'
Straight to the point, thank you.
Hi, thanks for your video. It's easy to understand. you have a new fan!!
thanks
Hi Tuomo, great vid! I am very curious about which VSCode color theme you're using since it looks really nice. Thanks in advance and love from The Netherlands.
Where did half the pixels go?
I want more videos Java script easily catch him my mine … Love from India 🇮🇳
please make a video about protected routes using next auth
Moi Tuomo, I recently discovered your channel, thanks for creating great content. I hooe you will upload more regularly.
all your video is best 🤩 I have one question can we create complete and advanced auth(send signup email link , sign in , forgot the password) with next-auth? ara you know which video on youtube is great for things i say , if it has not can you please do a video for that 🙏
Can you please do a video on Next Auth with Credentials provider and protect API routes with JWT & Cookies?