Next.js Discord

Discord Forum

Middleware setup

Unanswered
Russian Blue posted this in #help-forum
Open in Discord
Russian BlueOP
Hey guys, I have authentication setup on an external api and am handling it on the frontend without a package (any suggestions on packages other than next-auth?). The issue is I don't feel like the middleware is behaving correctly so if you can help me set it up I would greatly appreciate it.

2 Replies

Russian BlueOP
middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { decrypt, updateSession } from "./lib/auth";
import { cookies } from "next/headers";
const publicRoutes = ["/"]; //all routes by default are protected except for the ones in this list
const authRoutes = ["/login", "/signup"];
export async function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;
  const isPublicRoute = publicRoutes.includes(path);
  const isAuthRoute = authRoutes.includes(path);

  const cookie = req.cookies.get("session")?.value;
  if (!cookie) {
    console.log("here");
    return await updateSession(req);
  }
  const session = await decrypt(cookie as string);
  if (session && isAuthRoute) {
    return NextResponse.redirect(new URL("/", req.url));
  }
  if (!session && !isPublicRoute) {
    console.log("here");
    return NextResponse.redirect(new URL("/login", req.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};