Next.js Discord

Discord Forum

My attempt to create middleware NextJs v 14+ NextAuth v4+

Unanswered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Dwarf CrocodileOP
So idea is to make sure user cant change the path in browser by manual putting in other guilds id
import { NextResponse } from "next/server";
import { decode } from "next-auth/jwt";
export { default } from "next-auth/middleware";

export const config = {
  matcher: ["/guilds/:path*"],
};

export async function middleware(request) {

  const cookieHeader = request.headers.get("cookie") || "";
  const cookies = cookieHeader.split("; ");

  let tokenParts = cookies
    .filter((cookie) => cookie.trim().startsWith("next-auth.session-token."))
    .sort((a, b) => {
      const aPart = parseInt(a.split(".")[2].split("=")[0]);
      const bPart = parseInt(b.split(".")[2].split("=")[0]);
      return aPart - bPart;
    })
    .map((cookie) => cookie.split("=")[1]);

  const fullToken = tokenParts.join("");

  const decoded = await decode({
    token: fullToken,
    secret: process.env.NEXTAUTH_SECRET,
  });
  const guildIdArray = decoded.guilds.map((id) => id.id);
  const serviceIdArray = decoded.serviceId;

  const pathname = request.nextUrl.pathname;
  const test = pathname.split("/");

  const discordId = pathname.split("/")[2];
  const serviceId = pathname.split("/")[3];

  if (test.length === 3) {
    if (!guildIdArray.includes(discordId)) {
      return NextResponse.redirect(new URL("/", request.url));
    }
  }

  if (test.length > 3) {
    if (
      !guildIdArray.includes(discordId) &&
      !serviceId.includes(serviceIdArray)
    ) {
      return NextResponse.redirect(new URL("/", request.url));
    }
  }

  if (!request.url) {
    return NextResponse.redirect(new URL("/", request.url));
  }
}

export const configDashboard = {
  matcher: "/guilds/[discordId]/:path*",
};


this works! but again is this right way to do it?

please advice!!

0 Replies