DEV Community

Venkata Ravindra
Venkata Ravindra

Posted on

Next js auth middleware

Sure, you can add the middleware directly in the root folder of your Next.js app. To do that, create a file called middleware.js in the root folder and define your middleware function there. Here's an example:

import { getSession } from "next-auth/react";

export default async function middleware(req, res, next) {
  const session = await getSession({ req });

  // Check if the user is authenticated
  if (!session) {
    // User is not authenticated, redirect to the login page or show an error message
    return res.redirect("/login");
  }

  // If the user is authenticated, proceed to the next middleware or route handler
  return next();
}
Enter fullscreen mode Exit fullscreen mode

In this example, the middleware function checks if the user is authenticated using getSession from NextAuth. If the user is not authenticated, it redirects them to the login page or shows an error message. If the user is authenticated, it proceeds to the next middleware or route handler.

To use this middleware for protected routes, you can import it in your Next.js pages or API routes and apply it as middleware. Here's an example:

import middleware from "../middleware";

export default function ProtectedPage() {
  // Apply the middleware to the page
  return (
    <div>
      <h1>This is a protected page</h1>
    </div>
  );
}

// Apply the middleware to the page
export async function getServerSideProps(context) {
  await middleware(context.req, context.res, async () => {
    // Proceed to the page logic
    return {
      props: {},
    };
  });
}
Enter fullscreen mode Exit fullscreen mode

In this example, the middleware function is imported and applied in the getServerSideProps function, which is a Next.js server-side rendering function. The middleware is applied before the page logic is executed, ensuring that only authenticated users can access the protected page.

Remember to adjust the routes and authentication logic according to your specific application and requirements.

Let me know if you have any further questions!

Top comments (0)