Encountering an issue during the initialization of the Google Passportjs

I recently made the switch from JavaScript to TypeScript in my server project and I'm currently tidying up some code. I decided to combine my Google Passport OAuth stuff and login routes into a single file, but it seems like I've broken something in the process. I'm encountering an error that I can't quite pinpoint or fix. Any help would be greatly appreciated!

The error is occurring in index.ts on the

server.express.use(auth.initialize())
line. Specifically, I'm getting the following error message:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'initialize' of undefined
. Can someone help me figure out what's causing this issue?

index.ts

import { createTypeormConn } from './db/createConn'
import schema from './graphql'
import { pubsub } from './graphql/PubSub'
import * as auth from './middleware/auth'
const express = require('express')
const { GraphQLServer, PubSub } = require('graphql-yoga')
const cookieSession = require('cookie-session')
const cors = require('cors')
const path = require('path')

export const startServer = async () => {
    await createTypeormConn()
    const corsOptions = {
        origin: [
            //omitted for brevity
        ],
        credentials: true
    }

    const options = {
        port: process.env.PORT || 1337,
        endpoint: '/api',
        subscriptions: '/api',
        playground: '/playground'
    }

    const server = new GraphQLServer({
        schema,
        context: req => ({ pubsub, request: req.request })
    })

    server.express.use(
        cookieSession({
            maxAge: 24 * 60 * 60 * 1000,
            keys: [''] //omitted
        })
    )

    server.use(cors(corsOptions))
    server.express.options('/api', cors(corsOptions))
    server.express.use(auth.initialize()) //fails during initialize
    server.express.use(auth.session())
    server.express.use('/auth', auth.routes)
    server.express.use('/', express.static(path.join(__dirname, 'site')))
    server.start(options, ({ port }) => {
        console.log(`Server is running on localhost:${port}`)
    })
}
startServer()

auth.ts

import { User } from '../db/orm'
import * as passport from 'passport'
import { Router } from 'express'
import { OAuth2Strategy } from 'passport-google-oauth'

passport.serializeUser<any, any>((user, done) => {
    done(null, user.id)
})

passport.deserializeUser((id, done) => {
    User.findOne(id).then(user => {
        done(null, user)
    })
})

// passport.use(...)
// routes...
// export...

const initialize = passport.initialize
const session = passport.session
export { initialize, session, routes }

Answer №1

The context of this for passport is being lost. Make the following changes:

const start = passport.start
const end = passport.end

to:

const start = passport.start.bind(passport)
const end = passport.end.bind(passport)

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

`Error importing react-markdown in Next.js 11.1 with TypeScript``

Having trouble with importing react-markdown in my next.js SSG project. When running npm run dev, I encounter an error that prevents me from proceeding to test in next export. I understand that react-markdown is an esm package, but I'm not sure how t ...

Submit a Post request with a file and JSON information included

I'm encountering an issue while trying to pass files with a JSON object. It seems like there might be an error in the controller where the 'consumes' and 'produces' declarations are possibly incorrect. I need assistance on how to a ...

Unable to send a post request with an array in Node.js

As a novice, I've been struggling for days with a challenging problem that has me completely stuck. Essentially, my goal is to make a post request using node and express. The object needs to be created dynamically, but in my current scenario, I have ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

Prevent caching of JavaScript variables in EJS mode

Is there a way to turn off ejs cache? I came across a solution: ejs.clearCache() However, this method requires an instance of ejs to work. Currently, I am only using: app.set('view engine', 'ejs'); Therefore, I am unsure how to cle ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...

Is it possible to utilize npm request multiple times within a single route and showcase the outcomes on a single page?

Is it possible to utilize the node module "request" multiple times within a single route, and have the outcomes presented on a solitary rendered ejs template page? Objective: The aim is to exhibit eBook details from the iTunes Store by utilizing their Sea ...

I am encountering an issue with the connection between my Node.js web application and a MongoDB Atlas cluster

I encountered an issue with my MongoDB cluster. Initially, I connected my Node.js Express application to my MongoDB Atlas cluster, but it was not functioning correctly (I suspect the error originated from the MongoDB Atlas cluster because switching the con ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Introducing cutting-edge intellisense for Typescript Vue in VSCode, featuring automatic import functionality specifically designed for the

Currently, I am working on a small project using Typescript and Vue in VSCode. In my setup, I have TSLint, TSLint Vue, Vetur, and Prettier plugins installed. Unfortunately, I am facing an issue with the intellisense "auto import" feature. It does not seem ...

Even after rigorous type checking, TypeScript continues to throw the ts2571 error when handling an unidentified variable

Consider this scenario: the code snippet below will result in an Object is of type 'unknown'. error: let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Could be anything with the same structure let key = "he ...

Enhancing Node.js Using EJS Helper Functions

Can you set up helper functions in EJS templates that can be accessed from any EJS template? Here's how it could potentially work: app.js ejs.helpers.greetUser = function(name) { return 'Welcome, ' + name; }); index.ejs <%= greetU ...

Can you provide the syntax for a generic type parameter placed in front of a function type declaration?

While reviewing a project code recently, I came across some declarations in TypeScript that were unfamiliar to me: export interface SomeInterface<T> { <R>(paths: string[]): Observable<R>; <R>(Fn: (state: T) => R): Observable ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Error TS2304: Unable to locate identifier 'RTCErrorEvent'

I am currently working on a WebRTC application using Quasar, typescript and Vue. In my code snippet below, I am encountering an issue where I don't get any errors in WebStorm (as it uses the project's eslint config), and I can navigate to the def ...

How about combining Express API with SocketIO?

I am working on a ReactJS/Next application. I have successfully set up a separate REST API using Express and NodeJS on a different port. The API responds to requests made by my React app for specific endpoints. In addition, I am planning to integrate soc ...

Identify the individual who accessed a hyperlink within an email

My team is planning a small experiment involving sending an email to around 50 employees. The email will contain a link to a website stored on our local server, and I want to be able to track exactly who clicks the link by matching it with their email addr ...

Angular.js and ExpressJS combination results in a 404 error for a POST request

Currently, I am attempting to make a request to my ExpressJS server using AngularJS: angular.module('app').controller('contactCtrl', function($scope, $http) { $scope.envoyer = function(nom, organisation, courriel, telephone, messag ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...