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

126
Vistas
passport.authenticate() isn't redirecting

I have a problem with passport middleware, when I am authenticating a user it doesn't redirect I have no idea what's wrong.

Here is the code and whole project on GitHub:

const express = require("express");
const router = express.Router();
const passport = require("passport");
const genPassword = require("../passwordUtils").genPassword;
const connection = require("../database");
const User = connection.models.User;
// const logRegController = require("../controllers/log-reg-controller");

router.post(
  "/login",
  passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/register",
  })
);

router.post("/register", async (req, res) => {
  const existingUser = await User.findOne({ username: req.body.username });
  if (existingUser) return res.json({ message: "User already exists" });

  const saltHash = genPassword(req.body.password);

  const { salt, hash } = saltHash;

  const newUser = new User({
    username: req.body.username,
    hash: hash,
    salt: salt,
  });

  newUser.save().then((user) => console.log(user));

  res.status(201).json({ message: "All good" });
});

module.exports = router;

https://github.com/Oliwier965/Photo-App/tree/main

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

0

Dear StackOverflow community, this was a challenging battle but I come from it with an answer.

The problem was that I was sending post request using javascript fetch() which is an interface for making AJAX requests. And it is specifically designed to not change your URL. My solution is to send the URL that I want to redirect through res.json() with status 302 and redirect using the frontend. Hope it will help someone I attach the code below.

BACKEND

router.post("/login", function (req, res, next) {
  passport.authenticate("local", function (err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.status(302).json({ redirectUrl: "/register" });
    }
    req.logIn(user, function (err) {
      if (err) {
        return next(err);
      }
      //If Successful
      return res.status(302).json({ redirectUrl: "/" });
    });
  })(req, res, next);
});

FRONTEND

const login = async function (e) {
  e.preventDefault();
  const username = loginForm.querySelector("#email").value;
  const password = loginForm.querySelector("#password").value;

  const response = await fetch("/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      username,
      password,
    }),
  });

  const result = response.json();

  const data = await result;

  const { redirectUrl } = data;

  window.location.href = redirectUrl;
};

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try it with a callback function that redirects you can do it like this according to Docs

router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/register'); }
    req.logIn(user, function(err) {
        if (err) { return next(err); }
        //If Successful
        return res.redirect('/');
    });
    })(req, res, next);
});
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