Closed
Description
Anyone have success getting the middleware to work with next-auth v5? I am wrapping the middleware in auth, but the req.url is whatever we set the AUTH_URL
to be.
import { NextResponse } from "next/server";
import { auth } from "@nourish/auth";
import { env } from "~/env";
import { authRoutes } from "~/routes";
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /_static (inside /public)
* 4. all root files inside /public (e.g. /favicon.ico)
*/
"/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)",
],
};
export default auth((req) => {
const url = req.nextUrl;
const isLoggedIn = !!req.auth;
console.log(isLoggedIn, "isLoggedIn");
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
let hostname = req.headers
.get("host")!
.replace(".localhost:3000", `.${env.NEXT_PUBLIC_ROOT_DOMAIN}`);
// special case for Vercel preview deployment URLs
if (
hostname.includes("---") &&
hostname.endsWith(`.${process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX}`)
) {
hostname = `${hostname.split("---")[0]}.${env.NEXT_PUBLIC_ROOT_DOMAIN}`;
}
const searchParams = req.nextUrl.searchParams.toString();
// Get the pathname of the request (e.g. /, /about, /blog/first-post)
const path = `${url.pathname}${
searchParams.length > 0 ? `?${searchParams}` : ""
}`;
console.log(hostname, path, url, req.url);
// Handle app subdomain
if (hostname == `app.${env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
if (!isLoggedIn && path !== "/signin") {
return NextResponse.redirect(new URL("/signin", req.url));
} else if (isLoggedIn && authRoutes.includes(path)) {
return NextResponse.redirect(new URL("/", req.url));
}
return NextResponse.rewrite(
new URL(`/app${path === "/" ? "" : path}`, req.url),
);
}
// Handle main domain
if (
hostname === "localhost:3000" ||
hostname === env.NEXT_PUBLIC_ROOT_DOMAIN
) {
return NextResponse.rewrite(
new URL(`/home${path === "/" ? "" : path}`, req.url),
);
}
// Allow normal processing for all other requests
return null;
});
Metadata
Metadata
Assignees
Labels
No labels