Table of Contents
Protecting API routes is essential for securing your application and ensuring that only authorized users can access certain data or perform specific actions. In this guide, we will walk you through the steps to protect API routes in a Next.js application.
Prerequisites
Ensure you have the following installed:
- Node.js
- npm or yarn
- A Next.js project
Steps for Protecting API Routes in Next.js
Step 1: Setting Up the Next.js Project
If you don’t have a Next.js project set up already, you can create one using the following command:
npx create-next-app my-nextjs-api-protection # or yarn create next-app my-nextjs-api-protection
cd my-nextjs-api-protection
Step 2: Creating an API Route
First, let’s create a simple API route. Create a file hello.js in the pages/api directory:
// pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello, world!' }); }
You can test this route by navigating to http://localhost:3000/api/hello in your browser.
Step 3: Installing Authentication Library
We will use next-auth for authentication. Install it using npm or yarn:
npm install next-auth # or yarn add next-auth
Step 4: Setting Up NextAuth.js
Create a […nextauth].js file in the pages/api/auth directory to configure NextAuth.js:
// pages/api/auth/[...nextauth].js import NextAuth from 'next-auth'; import Providers from 'next-auth/providers'; export default NextAuth({ providers: [ Providers.Credentials({ // The name to display on the sign-in form (e.g. 'Sign in with...') name: 'Credentials', credentials: { username: { label: "Username", type: "text" }, password: { label: "Password", type: "password" } }, authorize: async (credentials) => { // Add logic here to look up the user from the credentials supplied const user = { id: 1, name: 'John Doe', email: 'john@example.com' }; if (user) { // Any object returned will be saved in `user` property of the JWT return Promise.resolve(user); } else { // If you return null or false then the credentials will be rejected return Promise.resolve(null); } } }) ], pages: { signIn: '/auth/signin', }, callbacks: { async jwt(token, user) { if (user) { token.id = user.id; } return token; }, async session(session, token) { session.user.id = token.id; return session; } } });
Step 5: Creating a Sign-In Page
Create a signin.js file in the pages/auth directory:
// pages/auth/signin.js import { providers, signIn, getSession } from 'next-auth/client'; import { useEffect } from 'react'; export default function SignIn({ providers }) { return ( <div> <h1>Sign In</h1> {Object.values(providers).map(provider => ( <div key={provider.name}> <button onClick={() => signIn(provider.id)}> Sign in with {provider.name} </button> </div> ))} </div> ); } export async function getServerSideProps(context) { const providers = await providers(); const session = await getSession(context); if (session) { return { redirect: { destination: '/' } }; } return { props: { providers } }; }
Step 6: Protecting the API Route
To protect the hello.js API route, we need to add authentication checks. Modify the hello.js file as follows:
// pages/api/hello.js import { getSession } from 'next-auth/client'; export default async function handler(req, res) { const session = await getSession({ req }); if (!session) { res.status(401).json({ message: 'Unauthorized' }); return; } res.status(200).json({ message: 'Hello, world!' }); }
Step 7: Testing the Protected Route
- Start your Next.js application:
npm run dev # or yarn dev
- Navigate to http://localhost:3000/api/hello. You should see an “Unauthorized” message if you’re not signed in.
- Sign in using the credentials you configured by navigating to http://localhost:3000/auth/signin.
- After signing in, navigate back to http://localhost:3000/api/hello. You should now see the “Hello, world!” message.
Conclusion
In this guide, we covered how to protect API routes in a Next.js application using next-auth for authentication. By following these steps, you can ensure that only authenticated users can access certain API routes, enhancing the security of your application.
For more updates on programming trends and tutorials, visit blogsea.net regularly.
Protecting API Routes in Next.js – FAQs
Protecting API routes ensures that only authorized users can access specific endpoints.
NextAuth.js is a popular library for handling authentication in Next.js.
Start your Next.js application, sign in via the sign-in page, and then access the protected route.
Yes, you can reuse the authentication logic in multiple API routes by creating a middleware function.
Configure the session object in the NextAuth.js options to set session duration and handling.