Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Express res.redirect redirect not working as expected

I have an express app. I am adding a middleware which redirects user to logout if token is invalid.

export async function validateAuthTokenMiddleware(
    req: Request,
    res: Response,
    next: NextFunction,
): Promise<NextFunction | void> {
    try {
        const { context } = req;
        await validateToken(context);
        next();
    } catch (err) {
        logoutAndRedirectUser(res);
    }
}

Code for logoutAndRedirectUser

const logoutUser = (res: Response) => {
    res.clearCookie('my_token')
    res.format({
        json: () =>
            res.status(401).json({
                errors: [
                    {
                        message: 'You must login to see this',
                        errorCode: '0001',
                    },
                ],
                extensions: {
                    location: location,
                },
            }),
        html: () => res.redirect(302, location),
        default: () => res.redirect(302, location),
    });
};

I am using this middleware in my route like so. All api request from client goes via this route:

router.use('/api', validateAuthTokenMiddleware, graphql);

However the redirect is not working as expected.

  • I am expecting my browser to get redirect to my '/login' route/page after clearing cookie. Instead I see just 401 for my /api call and browser remains on same page. res.redirect(302, '/login') is not triggered.
  • I have tried refactoring logoutUser to just send res.redirect(302, '/login') Instead of res.json. Still doesn't work.

Network snapshot as observed on browser: enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

My browser makes simple requests with

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,...

This means that application/json is acceptable (because of */*;q=0.8), therefore your json response is chosen, which is not a redirect. Perhaps reordering the choices within res.format helps.

You wrote:

I have tried refactoring logoutUser to just send res.redirect(302, '/login') Instead of res.json. Still doesn't work.

Can you share your refactored code as well, please?

about 4 years ago · Juan Pablo Isaza Denunciar

0

I end up setting a condition on my Client code. If received 401, redirect to login page.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda