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

Navigate to your project directory

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

  1. Start your Next.js application:
npm run dev
# or
yarn dev
  1. Navigate to http://localhost:3000/api/hello. You should see an “Unauthorized” message if you’re not signed in.
  2. Sign in using the credentials you configured by navigating to http://localhost:3000/auth/signin.
  3. 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

What is the purpose of protecting API routes in Next.js?

Protecting API routes ensures that only authorized users can access specific endpoints.

Which library is recommended for authentication in Next.js? 

NextAuth.js is a popular library for handling authentication in Next.js.

How do I test the protected API routes?

Start your Next.js application, sign in via the sign-in page, and then access the protected route.

Can I protect multiple API routes using the same authentication logic?

Yes, you can reuse the authentication logic in multiple API routes by creating a middleware function.

How do I handle session expiration in NextAuth.js?

Configure the session object in the NextAuth.js options to set session duration and handling.

Newsletter

I am a Software developer

My name is muhammad adnan and i am a professtional software developer. specialize in designing and developing efficient software applications.

Check out My Portfolio