How to set up redirects for logged in users with the option to display a landing page
Unanswered
Barbary Lion posted this in #help-forum
Barbary LionOP
Hi, I'm working on a project in Next.js and ran into a small issue that I haven't been able to solve. I want to set up a behavior similar to Vercel, where domain.app redirects a logged-in user to the dashboard, which works fine. However, I'd also like logged-in users to be able to access the landing page by visiting something like domain.app/home, but this still redirects to the dashboard.
Currently I have the following file structure:
current middleware:
Currently I have the following file structure:
/
- layout.tsx
- auth
- api
- (marketing) - Landing page
-> page.tsx
- (protected) - Dashboard
->page.tsxcurrent middleware:
import NextAuth from 'next-auth';
import authConfig from '@/auth.config';
import { NextRequest, NextResponse } from 'next/server';
import {
DEFAULT_LOGIN_REDIRECT,
apiAuthPrefix,
authRoutes,
protectedRoutes,
} from '@/routes';
const { auth } = NextAuth(authConfig);
interface AuthenticatedRequest extends NextRequest {
auth?: any;
}
export default auth((req: AuthenticatedRequest) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isProtectedRoute = protectedRoutes.some(route => new RegExp(route).test(nextUrl.pathname));
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLoggedIn) {
return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return;
}
if (!isLoggedIn && isProtectedRoute) {
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return NextResponse.redirect(
new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl)
);
}
return;
});
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};