Error: The function req.logIn is not valid

I'm currently in the process of creating a dashboard for my Discord bot, but I've encountered an error that reads as follows:

TypeError: req.logIn is not a function
    at Strategy.strategy.success (C:\Users\joasb\Desktop\Bot\node_modules\passport\lib\middleware\authenticate.js:247:13)
    at verified (C:\Users\joasb\Desktop\Bot\node_modules\passport-oauth2\lib\strategy.js:189:20)
    at Strategy._verify (C:\Users\joasb\Desktop\Bot\strategies\discord.js:38:24)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Below are the contents of my files: app.js:

require('dotenv').config()
require('./strategies/discord');

const express = require('express');
const passport = require('passport');
const app = express();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3002;
const routes = require('./routes');

mongoose.connect(`${process.env.DATABASE_URL}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

app.use('/api', routes); 
app.use(passport.initialize());   
app.use(passport.session());

app.listen(PORT, () => console.log(`Running on port ${PORT}`));

And discord.js

const passport = require('passport');
const DiscordStrategy = require('passport-discord');
const UserDB = require('../database/Schemas/UserDB');

passport.serializeUser((user, done) => {
    done(null, user.discordId)
});

passport.deserializeUser(async (user, done) => {
    try {
        const user = await UserDB.findOne({ discordId });
        return user ? done(null, user) : done(null, null);
    } catch (err) {
        console.log(err)
        done(err, null);
    }
});


passport.use(
    new DiscordStrategy({
        clientID: process.env.DASHBOARD_CLIENT_ID,
        clientSecret: process.env.DASHBOARD_CLIENT_SECRET,
        callbackURL: process.env.DASHBOARD_CALLBACK_URL,
        scope: ['identify', 'guilds'],
    }, async (accesToken, refreshToken, profile, done) => {
        try {
            const { id, username, discriminator, avatar, guilds } = profile;
            console.log(id, username, discriminator, avatar, guilds);
            const findUser = await UserDB.findOne({ discordId: id }, {
                discordTag: `${username}#${discriminator}`,
                avatar,
                guilds: guilds.length,
            });
            if (findUser) {
                console.log(`User was found!`);
                return done(null, findUser);
            } else {
                const newUser = await UserDB.create({
                    discordId: id,
                    discordTag: `${username}#${discriminator}`,
                    avatar,
                    guilds: guilds.length,
                });
                return done(null, newUser);
            }
        } catch (err) {
            console.log(err);
            return;
        }
    })
);

I have also implemented multiple strategies which are functioning properly. I am able to authorize my client, but the error occurs afterwards and causes a crash. Do you have any suggestions on how I can resolve this issue?

EDIT: satvik choudhary recommended that I include the package.json file, so here it is:

{
  "name": "quabot-db",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "mongoose": "^6.0.14",
    "passport": "^0.5.0",
    "passport-discord": "^0.1.4"
  }
}

Answer №1

Your middleware order is not correct. You have passport being initialized after handling API routes, which means when you try to use req.logIn in your route, it won't work because passport hasn't been set up yet!

To fix this issue, you should reverse the order like this:

app.use(passport.initialize());   
app.use(passport.session());

app.use('/api', routes);

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

Struggling to retrieve the Object from a JSON file located at a specific URL

Apologies if this comes across as naive, but my venture into javascript and json is just starting. I'm eager to access the JSON object from the twitter API after executing var myjson; $.getJSON('url of the Object', function(data) { ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

Enhance videojs player source with personalized headers

Currently, I have a backend API running on Express that manages a streaming video m3u8 file. The endpoint for this file is: http://localhost:3000/api/stream.m3u8 It is important to note that access to this endpoint requires a valid user token. router r ...

Issue when transmitting information from Angular to Express

I'm attempting to send data from Angular to Express.js Below is my TypeScript function connected to the button: upload(): void { const nameFromId = document.getElementById('taskName') as HTMLInputElement; this.taskName = nameFromI ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

Flickering issue with Chart.js chart persists upon reopening the page

Utilizing mustache.js, I am injecting a view file into a designated <div>. Within this view, I have incorporated a canvas element situated inside a specific div, showcasing a chart created with Chart.js. <div> <canvas id="gesundheitsve ...

Encountering a React npm start issue following the installation of MongoDB

I've been engaged in a simple project to get more familiar with react. I made the decision to incorporate mongoDB into my project, but since installing it, my app refuses to start. The odd thing is that I haven't even added any code for my app to ...

Link rows to dictionary keys and show their corresponding values

In my React component, I have a list of dictionaries stored in the props as follows: console.log(fruits): [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ] The dictionary entries are: 0: name: 'Apple' color: 'Red&apos ...

The issue encountered while uploading files using Ionic's native file transfer feature to a Node.js Express server is that the `

I'm new to developing with the ionic framework. Here's the flow of my ionic app: - Choose an image from folders and click on the "upload a picture" button. - I utilized Ionic Native File Transfer for uploading to a Node.js express server. This ...

Tampermonkey feature: Extract source code with a button click from a constantly updating AJAX page

My goal is to create a simple script that can copy the source code of a dynamic AJAX page whenever I press a button. The current code, which I have included below, seems to be working fine: // ==UserScript== // @require http://ajax.googleapis.com/ajax/li ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Flashing Effect of Angular Ui-Bootstrap Collapse During Page Initialization

Below is the code snippet I've implemented to use the ui-bootstrap collapse directive in my Angular application. HTML: <div ng-controller="frequencyCtrl" style="margin-top:10px"> <button class="btn btn-default" ng-click="isCollapsed = ...

Retrieving information from a TableRow element within Material UI

In the latest version of Material UI, I am utilizing a Table component but struggling to figure out how to fetch data from a selected row. The Table component's documentation mentions an onRowSelection prop that provides only the RowNumber of the sel ...

Is there a way to apply toggling and styles to only the card that was clicked in Vue.js?

DisplayBooks.vue consists of a single page responsible for showcasing books fetched from a backend API. Each card on the UI features two buttons - ADD TO BAG and ADDED TO BAG. When a user clicks on the ADD TO BAG button of a specific card, it should toggle ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

The argument passed is of the type 'Session | undefined', which cannot be assigned to a parameter of type 'Session'

Let me simplify the code for you: npm install express express-cookies @types/cookie-session @types/express-session import express from express(); import cookieSession from 'cookie-session'; const app = express(); app.use(cookieSession({ ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

Interested in transferring an additional column value to the $scope.seriesSelected variable?

I've been delving into Timeline charts using the angularjs google chart API and have come across an interesting limitation. It seems that only 4 columns are allowed, with the extra column designated for tooltips. However, I have a specific requirement ...

Async express config within GCP Cloud Function

I have a situation where I want to transition my express server into a serverless Cloud Function while incorporating Cloud Logging. Following the guidance provided in the Cloud Logging tutorial, I am required to refactor the configuration of my server into ...

Getting callback data from a function in the AWS SDK without using asynchronous methods

I have a code snippet that fetches data from AWS using a function: main.js const { GetInstancesByName } = require("./functions"); var operationmode = "getinstances"; if (operationmode == "getinstances") { let getresult = ...