Next.js Discord

Discord Forum

Multi-session redirect with middleware.ts

Unanswered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Orinoco CrocodileOP
const getSessions = (cookieValue: string) => {
  if (!cookieValue) return {} as Record<string, any>;
  try {
    return JSON.parse(cookieValue) as Record<string, any>;
  } catch {
    return {} as Record<string, any>;
  }
};

export function middleware(request: NextRequest) {
  const { searchParams, pathname } = request.nextUrl;

  if (pathname === '/login') return NextResponse.next();

  // Avoid redirect logic during prefetch to reduce “laggy” navigation
  if (isPrefetchRequest(request)) return NextResponse.next();

  const userIndex = searchParams.get('u');
  const sessions = getSessions(request.cookies.get(SESSIONS_COOKIE)?.value || '');
  const availableSessions = Object.keys(sessions);
  const hasActiveSession = availableSessions?.length > 0;

  // SCENARIO A: No 'u' parameter provided
  if (userIndex === null) {
    if (hasActiveSession) {
      // Redirect to the first available user:?u=0
      const defaultIndex = availableSessions[0];
      const url = new URL(request.url);
      url.searchParams.set('u', defaultIndex);
      return NextResponse.redirect(url);
    }

    // No sessions at all -> Login
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // SCENARIO B: 'u' parameter exists but is invalid for this session map (e.g. ?u=99)
  if (!sessions[userIndex]) {
    if (hasActiveSession) {
      // Fallback to a valid user (prevent broken page)
      const firstValid = availableSessions[0];
      const url = new URL(request.url);
      url.searchParams.set('u', firstValid);

      return NextResponse.redirect(url);
    }

    // Invalid param AND no sessions -> Login
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // SCENARIO C: Valid User
  return NextResponse.next();
}


Can anyone tell me why is this middleware code slowing my app down. Also, how to handle the case if I'm in "/?u=1" and somewhere in my app router.push("/schemas"); happens
it is going to "/schemas?u=0" instead of "/schemas?u=1"

1 Reply

Orinoco CrocodileOP
I recently added multi account functionality and it affected my account. I am basically trying to build multi session support
like google ?u=0, ?u=1 etc. to differentiate

how to handle the case if I'm in "/?u=1" and somewhere in my app router.push("/schemas"); happens
it is going to "/schemas?u=0" instead of "/schemas?u=1"