I have set up a NEXTJS app that is under a subdomain and basically the structure is the following:
/Pages->
--/Sites
--/api
--/home
--/subdomain_logic
--_app.tsx
...config files...
As of this moment, if you go to domain.com you will be landing into another app that I developed so there is nothing configured outside of subdomain logic. If you go to subdomain.domain.com then you get all the logic ocurring into subdomain_logic. I want to set api routes but nextjs doesn't allow to set them outside of your api folder and if I leave them there those routes actually belong the domain.com app that I have in isolation. How would you create api routes on my situation?
Here is my middleware.ts file:
import { NextRequest, NextResponse } from "next/server";
export const config = {
matcher: [
"/",
"/([^/.]*)", // exclude `/public` files by matching all paths except for paths containing `.` (e.g. /logo.png)
"/site/:path*",
"/post/:path*",
"/_sites/:path*"
]
};
export default function middleware(req: NextRequest) {
const url = req.nextUrl;
const pathname = req.nextUrl.pathname.toString();
const hostname = req.headers.get("host");
if (!hostname)
return new Response(null, {
status: 400,
statusText: "No hostname found in request headers"
});
const currentHost =
process.env.VERCEL_ENV === `production` ||
process.env.VERCEL_ENV === `preview`
?
hostname
.replace(`.domain.com`, "")
.replace(`${process.env.VERCEL_URL}`, "")
.replace(`${process.env.NEXT_PUBLIC_VERCEL_URL}`, "")
: hostname.replace(`.localhost:3000`, "");
if (pathname.startsWith(`/_sites`))
return new Response(null, {
status: 404
});
if (
!pathname.includes(".")
) {
if (currentHost === "subdomain") {
if (
pathname === "/login" &&
(req.cookies["next-auth.session-token"] ||
req.cookies["__Secure-next-auth.session-token"])
) {
url.pathname = "/";
return NextResponse.redirect(url);
}
url.pathname = `/subdomain${url.pathname}`;
console.log(url);
return NextResponse.rewrite(url);
}
url.pathname = `${pathname}`;
return NextResponse.rewrite(url);
}
}
I would like to set up properly NextAuth if that give more clues into what could be the solution for my problem. Thanks for the help!