export default auth((req: NextAuthRequest) => {
const url = req.nextUrl;
const isLoggedIn = !!req.auth;
const isAuthRoute = authRoutes.includes(url.pathname);
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
let hostname = req.headers
.get('host')!
.replace('.localhost:3000', `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);
hostname = hostname.replace('www.', ''); // remove www. from 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}` : ''
}`;
if (hostname === `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
if (!isLoggedIn && !isAuthRoute) {
return NextResponse.redirect(new URL('/login', req.url));
} else if (isLoggedIn && isAuthRoute) {
return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, req.url));
}
// Continue to the next middleware or serve the root content
return NextResponse.rewrite(
new URL(`/app${path === '/' ? '' : path}`, req.url),
);
}
// rewrite root application to `/home` folder
if (
hostname === 'localhost:3000' ||
hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
) {
return NextResponse.rewrite(
new URL(`/home${path === '/' ? '' : path}`, req.url),
);
}
// rewrite everything else to `/[domain]/[path] dynamic route
return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));
});
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};