Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!