What is the best way to convert an Express route to Typescript?

I'm trying to create a wrapper called loginRequired for my Express route, but I'm struggling to define the right types.

This is what my loginRequired wrapper looks like:

export const loginRequired = (fn) => (req, res, next) => {
    // Check if unauthorized
    if (!req.session.currentUser) {
        return res.status(401).send({
            status: 'error',
            message: 'Login required'
        });
    }

    // If authorized, execute normally
    return fn(req, res, next);
}

Now I need to wrap my route handler:

app.get('/protected', loginRequired(req, res, next) => {
    return res.next({ secret: 'foo' });
});

Answer №1

import { Request, Response, NextFunction, RequestHandler } from 'express-serve-static-core';

export const authenticationRequired = (
    fn: RequestHandler
) => (
    req: Request, res: Response, next: NextFunction
): ReturnType<RequestHandler> => {
    if (!req.session.currentUser) {
        return res.status(401).send({
            status: 'error',
            message: 'Authentication required to access this resource'
        });
    }
    return fn(req, res, next);
};

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

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this. Let's assume there exists a class class Foo { bar: string; baz: number; bob: a ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Error: Unexpected input detected in `ts.resolveTypeReferenceDirective`. This issue may lead to a debug failure

I'm encountering the error below: { "name": "Angular", "version": "1.0.0", ... } If anyone has insights on what steps to take next or the potential cause of the problem, your input would be greatly a ...

Jasmine attempting to access a nonexistent property

I created a very basic component: import { Component } from '@angular/core'; @Component({ selector: 'loading', templateUrl: './loading.component.html', styleUrls: ['./loading.component.scss'] }) export ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

Having trouble installing express-generator

After visiting the http://expressjs.com guide, my attempt to install express-generator using the command below was unsuccessful. npm install express-generator -g I also tried switching up the order with npm install -g express-generator, but unfortunately ...

Express: Issue with Post Request handler causing repeated function calls

My application built with Express is supposed to call a function once, but it seems to be calling it an infinite number of times whenever it handles a POST request. I can't seem to figure out why it's being called more than once. This applicatio ...

Navigable outside graphic key in AmCharts version 4

Is it possible to achieve a scrollable legend in AmCharts 4 similar to this AmCharts 3 tutorial? With the absence of legend.divId in AmCharts 4, controlling legend size seems challenging as it is all rendered as a single SVG element with limited control us ...

Enhancing Luxon DateTime with extension type support

Referencing the issue at https://github.com/moment/luxon/issues/260, I am looking to extend the DateTime object as shown below: import { DateTime } from 'luxon'; function fromUnix(tsp?: number): DateTime { return DateTime.fromMillis(tsp * 1000 ...

Utilizing API routes within your React application

After creating my own API using nodejs, express and mongoDB, I successfully tested the routes with postman. However, I am struggling to integrate these routes into my react app for CRUD operations on the data. Despite having previous experience working wit ...

Assign the chosen value to the dropdown list if ngModel is present

I currently have a select field implemented in my Angular component: <select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)"> <option class="form-con ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Identifying Shifts in Objects Using Angular 5

Is there a way to detect changes in an object connected to a large form? My goal is to display save/cancel buttons at the bottom of the page whenever a user makes changes to the input. One approach I considered was creating a copy of the object and using ...

The compatibility issues between Angular 5 and materialize-css (v 1.0.0) are causing obstacles in functionality

I attempted to implement the solution found on this post: Unfortunately, the solution didn't work as expected. I am working with Angular and Typescript in my project. Here is a snippet of my Typescript class: import { Component, OnInit, AfterVi ...

The term "Movie" is not compatible as a JSX component

Currently working on a movie app project but encountering issues with handling arguments and displaying them properly using TypeScript. The challenge lies in trying to map the movie object, display them individually on the homepage, and showcase all the re ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...

Do not include the node_modules directory in the TypeScript compilation process, except for a specific subdirectory that is

To exclude the entire node_modules directory from TypeScript compilation, you can modify the tsconfig.json file like so: { "compilerOptions": { "module": "commonjs", "sourceMap": true, "target": "es6" }, "exclude": [ ...

The type of 'data' is assumed to be 'any[]' without being explicitly stated

I am encountering several type errors in the function below, and as a newcomer to Typescript, I'm unsure about how to fix them. private fetchFromUrl = () => { var data = [] fetch(`${process.env.PUBLIC_URL}/tempData/monthly.csv`) .t ...

How to update the page title in React TypeScript 16.8 without using Helmet

I have created a custom 404 not found page, and I would like the title of the page to change when someone navigates to it. Unfortunately, I do not want to use Helmet for this purpose, but I am struggling to make constructor or componentDidMount() work in ...