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

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Struggling to traverse through intricate layers of nested objects in React and showcasing them without going crazy

Dealing with an API that returns data structured in deeply nested objects has been a challenging task. The goal is to extract specific data from these nested objects and then display them within a React project. Despite numerous attempts, finding a simple ...

Extract information from a webpage using Selenium WebDriver

Currently, I am working on mastering Selenium, but I have hit a roadblock that I need assistance with. My task is to gather all the betting information for games from the following link and store it into an array. Given my limited experience with HTML an ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...

Could a javascript loop be created to continuously activate a button with each iteration?

I have just started learning javascript and I am in the process of creating a website where users can change the background by simply clicking on a button. It's working perfectly fine so far, but I want to add another feature where the background imag ...

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

Is there a way to use AJAX for transferring a value?

I am looking to transmit a value to a php-script (servo.php) that will then write the received data in a file (/dev/servoblaster). The script section of my HTML file (index.html): <script> function tiltt() { var tilt = document.getElementById("tilt ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Steps for displaying a bootstrap modal in alignment with the triggering button's position

Recently diving into the world of bootstrap and AngularJs has been quite the learning experience for me. One challenge I encountered was trying to implement a bootstrap modal dialog box to show additional details within a table column. My goal was to hav ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

How to enhance an existing JSON object by including a new attribute in a Node.js environment

Here is an object that I am working with: ==================records=========={ Id: 5114a3c21203e0d811000088, userId: 'test', sUserId: test, userName: 'test', url: 'test', Title: 'test' } I am trying to ad ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

Utilizing Angular's Local Storage Module to efficiently store and manage various elements within an array in Local Storage

I'm facing an issue with storing and retrieving an array from localStorage using the Angular Local Storage Module. Despite following the necessary steps, I am only able to retrieve the last element added to the array. Can anyone provide insights on wh ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

The Mysteries of Key Codes in JavaScript

I'm curious about the character codes used for keyboards. Recently, I came across an informative article discussing this topic. In particular, I am interested in finding out which key code to use when a user presses both the alt and down arrow keys s ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

Utilizing API data to set the state in a React component

In my quest to modify the state of this React component, I have a variable called rankAndTeam that holds the "prints=>" data listed below. My goal is to assign "Washington Capitals" to this.state.teamRank["0"], "New York Islanders" to this.state.teamRank[" ...