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.
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\twith import default middleware
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