#Multi-session redirect with middleware.ts

1 messages · Page 1 of 1 (latest)

tribal sphinx
#
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"

loud archBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)