What is the correct way to handle JSON responses with passport.js?

In my Express 4 API, I am using Passport.js for authentication. While most things are working fine, I have encountered difficulty in sending proper JSON responses such as error messages or objects with Passport. An example is the LocalStrategy used for logging in:

passport.use(
    'login',
    new LocalStrategy(
        {
            usernameField: 'email',
        },
        (email, password, done) => {
            User.findOne({ email: email }, (err, foundUser) => {
                if (err) return done(err);

                if (!foundUser) {
                    return done(null, false, {
                        message: 'Invalid Username.',
                    });
                }

                if (!foundUser.comparePassword(password)) {
                    return done(null, false, {
                        message: 'Invalid Password.',
                    });
                }

                return done(null, foundUser);
            });
})
);

Despite setting custom messages for authentication failure, these messages do not appear in my API responses. How can I send such messages when something goes wrong during authentication?

app.post(
    '/signup',
    passport.authenticate('signup', {
        successRedirect: '/user',
        failureMessage: true,
        successMessage: true,
    })
);

Furthermore, rather than setting redirects like successRedirect, I aim to deliver proper JSON responses for each scenario. In case of an error, I want to send it as a JSON object instead of redirecting to a route. Is there a way to achieve this?

Answer №1

Utilize the async await functionality in this scenario.

passport.use(
  'login',
  new LocalStrategy(
    {
      usernameField: 'email',
      passwordField: 'password',
    },
    async (email, password, done) => {
      try {
        const user = await User.findOne({ email });
        // If the user exists, the entire document will be returned, otherwise it will be null. You can now proceed to test your conditions based on this user flag */
      } catch (error) {
        done(error);
      }
    },
  ),
);

For the situation you mentioned previously, you can respond as follows:

app.post('/signup', passport.authenticate('login'), (req, res) => {
  res.status(200).json({
    message: 'Your custom message here',
    user: req.user,
  });
});

In this context, ensure that you use 'login' in the passport.authenticate('login') function since the local strategy is being used as indicated in the code above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send a parameter to an express.js Router?

Here's a unique spin on an example taken from Express.js's routing guide: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('Welcome to the home of Birds&ap ...

The post request seems to be functioning correctly in Postman, but encountering issues when attempted in

Upon sending SignUp and Login data via Postman, data is successfully stored in Mongodb and a success message is displayed. However, when the same request is made through React axios, an error appears in the console: POST http://localhost:1000/auth/signup ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

What is the process for dynamically altering the method in a class?

Is there a way to dynamically modify the changeThis method by substituting it with the value of a radio element? For example, if I select event1, the method should be switched to Class.event1() <input type="radio" class="radio-input" ...

finding it difficult to display my components when incorporating ROUTE in my ReactJS project

Can anyone help me with the code for app.js? I've been trying to implement ROUTE but my components are not rendering correctly. import './App.css'; import Home from './pages/Home'; import Rooms from './pages/Rooms'; impor ...

Converting a Base64 URL to an image object: A step-by-step guide

I currently have a base64 URL in the following format: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAA My objective is to convert this into an image file with the following properties: [File] 0: File lastModified: 1559126658701 lastModifiedDate: Wed M ...

What is the best way to ensure the parent element adjusts to fit its floated children, without exceeding the width of the window?

I am attempting to center a group of floating elements, but due to them being displayed in masonry style, I cannot set them as inline. It is clear that a container is necessary, but I have been unable to find information on how to achieve this: Please dis ...

Preventing scrolling on a YouTube video embed

I have been working hard on developing my personal website. One issue I encountered is that when there is a YouTube video embedded in the site, it stops scrolling when I hover over it. I would like the main document to continue scrolling even if the mouse ...

Maximizing the Efficiency of jQuery and Javascript Frameworks

Currently, I am working on a project that involves utilizing a JavaScript framework (jQuery) in conjunction with various plugins (validation, jquery-ui, datepicker, facebox, and more) to enhance the functionality of a modern web application. However, I ha ...

Error encountered with the '$' symbol in the SQL syntax

Currently, I am in the process of creating a PFP route using EXPRESS and PSQL. However, I have encountered a small issue. Upon running my code, an error message is displayed: "Syntax error at or near "$" The snippet of code triggering this error is sho ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

The refusal to run JavaScript stemmed from an empty MIME type, resulting from the combination of nodeJS, express, engintron, and nginx

Currently, I'm struggling with a frustrating issue that's making me want to pull my hair out. So, here's some important information you need to be aware of: My application is built using node.js (version 16.13.1) with express and nginx man ...

The module '@algolia/cache-common' is missing and cannot be located

summary: code works locally but not in lambda. My AWS lambda function runs perfectly when tested locally, utilizing Algolia within a service in the server. Despite installing @algolia/cache-common, any call to the lambda results in a crash due to the erro ...

- "Utilizing the _underscore loop within a design framework"

I am encountering a persistent error while working on this. Specifically, I keep receiving an error related to syntax: syntax error var _p=[],print=function(){_p.push.a... ');}return __p.join(''); <script id="product" type="text/t ...

Implementing dynamic title insertion into a popover element using jQuery

My goal is to assign a title to my popover object in a local project. I have already included the following files: bootstrap.css v4.2.1 jquery.min.js v2.2.0 bootstrap.min.js v4.2.1 popper.min.js v1.11.0 Initially, there was a basic button present. <i ...

The ajax success response transforms when using @html.raw

In my Razor viewpage, I have the following jQuery code: $(document).ready(function () { var listValues = @Html.Raw(Json.Encode(Session["list"])); $("#nsline").click(function () { alert(listValues) $.ajax({ type: "P ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Implementing an event listener on an anchor element dynamically inserted through Javascript

I made an Ajax call that retrieves a list of movie titles. I am trying to click on a button next to each title in order to add it to my "currently watching" list. However, my "add" link is not responding to the event handler. What steps can I take to suc ...

How to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...