Login as User route

Im currently trying to create a login as user route, wich works perfectly on production mode on localhost but not deployed on vercel.com

The route and session replacement works when i build it via npm run build and start it via npm run start on localhost:port but not via ip:port, but is completly unfunctional on my production deployment here on vercel.

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import UserProfile from '@/models/UserProfile';
import { encode } from 'next-auth/jwt';
import { cookies } from 'next/headers';

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);

  if (!session || !session.user || !session.user.isAdmin) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
  }

  const { userId } = await request.json();
  const user = await UserProfile.findById(userId);

  if (!user) {
    return NextResponse.json({ error: 'User not found' }, { status: 404 });
  }

  const token = await encode({
    token: {
      id: user._id.toString(),
      username: user.username,
      isProUser: user.isProUser ?? false,
      isAdmin: user.isAdmin ?? false,
      role: user.role,
      sessionToken: user.sessionToken,
    },
    secret: process.env.NEXTAUTH_SECRET!,
  });

  // Cookie löschen
  cookies().delete('next-auth.session-token');

  // Cookie setzen
  cookies().set('next-auth.session-token', token, {
    path: '/',
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'none',
    maxAge: 60 * 60 * 24,  // 24 Stunden
  });

  return NextResponse.json({ success: true }, { status: 200 });
}

Deployment URL or Custom Domain: clipstocommunity.de
Environment (production):production
Project Framework: nextjs

Node/Runtime Version:20
Package Manager: npm
Relevant Packages: next-auth

Hey @captainexory. Thanks for sharing the code snippet and project details!

If the function returns an error code, you can use that to get more info about what’s going wrong. The runtime logs might also have more details about what’s happening.

A try/catch statement is a good option to help the function gracefully handle errors and communicate the problem to site visitors. They can also help you figure out which part of the function is causing the problem.

If you’re still having trouble, please tell me more about what’s going wrong. Screenshots of the page and dev tools can help me see what you see so we can solve it together.

Sadly i get a „success: true“ response, but there is no session replacement happening.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.