Error: The function req.logIn is not recognized - Passport JS

After researching extensively, I am confident that the issue I'm facing is not a known bug. I am currently utilizing passport JS with the local strategy in my login route, employing a custom callback and invoking req.login once I confirm the user's existence. This approach is in line with the documentation's guidance:

Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response

Despite following the recommendations, I continually encounter an error indicating that req.logIn is undefined (Note that you can call either reg.login or req.logIn as they are aliased. I've also tried both). Strangely, my IDE is recognizing the typescript definitions, and I can verify the presence of the req.logIn function in the compiled app.js output. This discrepancy is perplexing.

app.ts

const localStrategy = LocalStrategy.Strategy;

passport.use(new localStrategy({
        usernameField: 'email',
        passwordField: 'password'
    },
    async function (email, password, done) {
        const member: IMember | null = await MemberModel.findOne({where: {email: email}});
        if (member) {
            bcrypt.compare(password, member.hash, function (err, res) {
                if (err) return done(null, false, {message: err.message});
                if (!res) {
                    return done(null, false, {message: 'Incorrect password.'});
                } else {
                    return done(null, member);
                }
            });
        }
        else {
            return done(null, false, {message: 'Couldn\'t find a matching user.'});
        }
    }
));

passport.serializeUser(function(user: IMember, done) {
    done(null, user.id);
});

passport.deserializeUser(async function(id: string[], done) {
    const user: IMember | null = await MemberModel.findOne({where: {id: id}});
    if (user) {
        done(null, user);
    }
});

// Initialize the app
const app: e.Express = express();

app.use(bodyParser.json());
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

app.post('/login', (req, res, next) => {
    passport.authenticate('local', (err, user, options) => {
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(options.message);
        }
        req.logIn(user, ((err) => { // <-- Errors on this line 
            if (err) {
                return next(err); }
            return res.redirect('/users/' + user.username);
        }));
    })(req, res, next);
});

Versions


    "express": "^4.17.1",
    "express-session": "^1.17.0",
    "passport": "^0.4.1",
    "passport-local": "^1.0.0",
    "typescript": "^3.7.4",
    "@types/express-session": "^1.15.16",
    "@types/passport": "^1.0.2",
    "@types/passport-local": "^1.0.33",
    "@types/express": "^4.17.2",

Answer №1

To properly implement passport middleware, make sure to initialize it before registering any routes:

app.use(passport.initialize());

Answer №2

req.signIn(user, ((err) => { // <-- Mistakes found on this line 
    if (err) {
        return next(err); }
    return res.redirect('/users/' + user.username);
}));

attempt req.login without using camelCase as suggested on

Answer №3

The reason for this error is due to the placement of `app.use(passport.initialize());` after the declaration of routes `app.use("/api",initWebRoutes);`. It is important to initialize the passport middleware before making any route calls to prevent this issue.

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 are the steps to locally test my custom UI library package built with tsdx in a React.js project

I am currently utilizing tsdx to develop a React UI library, and I am looking to test it within my Next.js project before officially publishing it to the npm package. Initially, I attempted using npm link, which worked initially. However, when I made ch ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

A parameter in Typescript must be provided if another parameter is set to true

Need help with TypeScript function parameters: myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: boolean = false, values: Array<any>) { console.log(allData); console.log(selectedData); console.log(onlyValu ...

Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Compiling TypeScript files from multiple source directories

Having 3 NodeJs applications with the latest versions of Typescript code, each containing an "src" folder with TypeScript code files and a "dist" folder with JavaScript files compiled by Typescript. I am now looking to create a "common" folder outside of ...

Looping through a detailed JSON array filled with objects to extract just a pair of items is essential. I aim to achieve this efficiently by utilizing LOD

Looking at this intricate JSON object... Here's a snippet of the code: entity: [{entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}] 0: {entityName: "Nrm", page: 0, p ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Steps for customizing the default properties of a material ui component

Is there a way to change the style properties listed on the main element? height: 0.01em; display: flex; max-height: 2em; align-items: center; white-space: nowrap; } <InputAdornment position="end" > {"hello& ...

Error in NextJS Middleware Server: Invalid attempt to export a nullable value for "TextDecoderStream"

I've recently created a straightforward Next.js application using bun (version 1.0.4, bun create next-app), incorporating app routing with Next.js version 13.5.4 and a designated source directory. My goal was to implement a middleware that restricts a ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

Attempting to revert the imported module back to its initial/default mock configuration

When working on my test file, I utilize a folder named mocks which contains various exported functions. Most of the time, I rely on the mocks folder to perform all necessary tasks. However, there is one scenario where I need to adjust the return value to a ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Using *ngFor to populate an array in an ion-list within Ionic 2

Hi there, I'm currently learning Ionic 2 and I recently created an array that I want to loop through in an ion-list. This is my produk.ts import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angul ...

Having trouble resolving all parameters for the component xyz: (?, ?) after the upgrade to Angular 2 CLI

After upgrading my Angular2 project from Beta .21 to beta .25.5, which was functioning smoothly, I resolved all errors for both AOT and non-AOT (e.g. ng serve) functionalities. However, upon browser loading, I encountered an error affecting multiple servi ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

"Encountered a runtime error while trying to execute the doubleClick() function using Pro

Encountering the following issue: "WebDriverError: Unable to convert: Error 404: Not found" while running a test with protractor: browser.actions().doubleClick(elem).perform(); or browser.actions().click(elem).click(elem).perform(); Uncertain of t ...

Using Angular 4 to monitor changes in two-way binding properties

Recently, I developed a unique toggle-sorting component that examines if the current sorting parameters align with its sorting slug and manages clicks to reflect any changes. // toggle-sorting.component.ts @Input() sortingSlug: string; @Input() currSorti ...

What is the best way to attach an EventListener to all DOM elements with a particular class?

Within my DOM, I have dynamically created spans that all have the class "foo". Utilizing TypeScript, I aim to attach an onClick event to each of these spans post-creation. Here is my current approach: var foos = document.body.querySelectorAll(".foo"); f ...