logomedCode
January 31, 2024

How to protect api routes in Next.js-middleware security

This tutorial delves into safeguarding routes within Next.js 13, employing three distinct approaches. Our exploration will cover the implementation of protective measures on both the client and server...
How to protect api routes in Next.js-middleware security

#Next.js #middleware #routes #API #framework

This tutorial delves into safeguarding routes within Next.js 13, employing three distinct approaches. Our exploration will cover the implementation of protective measures on both the client and server sides, along with the utilization of middleware. By the end of this guide, you'll have a comprehensive understanding of securing routes, equipping you to fortify the layers of defense for your Next.js applications.

1. Create a Middleware file

Use the file middleware.ts (or .js) in the root of your project to define Middleware. For example, at the same level as pages or app, or inside src if applicable.

export { default } from "next-auth/middleware";
export const config = {
  matcher: [
    "/dashboard/add-articles/:path*",
  ],
};

this example we protect this path:/dashboard/add-articles with import default middleware

2. API route.js (auth) file

in this example we have a social media auth :

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import GithubProvider from "next-auth/providers/github";


export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  pages: {
    signIn: "/dashboard/login",
  },
};


export const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };   


if it was useful don't forget to add comments and share

author image
AuthorMOHAMMED DAKIRContent Creatormohamed7dakir@gmail.com

This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy