What is the importance of having a generic Locals type Request in express?

As I was working on creating the properties of a Request object without using global declarations, I encountered a problem that threw me off course.

I attempted to utilize the generic Locals for Request in order to set up the req.auth property, but unfortunately, it resulted in an error. This has left me questioning the necessity of this generic. Here's a snippet of what I tried:

import { Request, Response, NextFunction } from "express";

interface Local {
  auth: {
    token: string;
    payload: Object;
  }
}

const example = function (req: Request<{}, {}, {}, {}, Local>, res: Response, next: NextFunction) {
  req.auth
  next();
};

Answer №1

One way to improve your code is by creating an interface that extends Request, rather than passing the interface directly to Request.

interface NewLocal extends Request {
  auth: {
    token: string;
    payload: Object;
  };
}


const newExample = function (req: NewLocal, res: Response, next: NextFunction) {
  req.auth;
  next();
};

If you examine the Request type closely, you'll notice that the fifth type is

Locals extends Record<string, any>
, specifically used for res.locals and not for req.

https://i.sstatic.net/LRRg2tod.png

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

Sending a post request with Unirest

I am trying to establish a connection between two servers, both running on the same device initially. Below is my current setup: const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const ...

Error Encountered: Visual Studio cannot locate the file 'COMPUTE_PATHS_ONLY.ts' during the build process

Upon fixing my visual studio 2015, an error was thrown that I haven't encountered before. Error Build: File 'COMPUTE_PATHS_ONLY.ts' not found. I did not add COMPUTE_PATHS_ONLY.ts to my Git repository. The other files in the repo rema ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Ensure that the user's credentials are accessible to all views in Node.js

I'm currently developing an Android application that utilizes Node.js web services. The initial interface requires the user to connect to a host using an IP address, login, and password in order to access all databases. I aim to save these credentials ...

How can we elegantly include req.headers.username in the log format when using the Node.js/Express/Winston logger?

Currently, my nodejs / Express js backend is utilizing the Winston logger. src/utils/logger.ts: import winston from 'winston' import moment from 'moment'; import os from 'os'; import process from 'process'; import r ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

The ngx-image-cropper in Angular only necessitates a button click, making the default cropper unnecessary

Currently, the image is cropped by default when loaded, but I would like the crop to only occur when the crop button is clicked. I tried searching on Google and found autoCrop:false, but I am unsure where to place it in the code. Below is the HTML code: ...

Encountered an error in production mode with Angular 7: Uncaught ReferenceError - "environment" variable

During development, my application runs smoothly, and ng build --prod --source-map successfully compiles the application. However, when attempting to access it through the browser, an error occurs: app.module.ts:47 Uncaught ReferenceError: env is not defi ...

There seems to be an issue with the compatibility between typescript and the current version (4.17.14) of the express-serve-static

Using "@types/express-serve-static-core": "4.17.13", the augmentation of express-serve-static-core is functioning properly: import { Request, Response, NextFunction } from 'express' import { PrismaClient } from '@prisma/c ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Issue: encountered an EADDRINUSE error stating that the address is already in use (8080) when attempting to run the script

After running the command npm ndb server.js, a debugging Chrome window appeared. However, I encountered some errors while trying to debug my code. When I clicked on "run script," another debugging Chrome window popped up and displayed these strange error ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

JavaScript Node Save User Details

I'm currently in the process of refactoring my code and everything is functioning perfectly with regards to saving a user and charging their credit card. What I want to achieve is delaying the user-saving step until the end of the function. Currently ...

What's the reason behind my REST API delivering a 401 error code?

New Update After being encouraged to implement debug logs, I have discovered that the issue lies with Spring reporting an invalid CSRF token for the notices controller. I have compared the headers generated by Postman and the fetch requests, but found no ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

Preventing Directive Angular 2 from Triggering Stop Button Click Event

I created my application using angular 2 and PrimeNG. I am trying to implement directives for checking user authority when a button is clicked. The issue I am facing is that even though there is no authority, the click event continues to be triggered. How ...

Issue: Data needs to be in the form of a string or buffer, and the salt must be either a salt string or a specified number of

While trying to hash the password using bcrypt and testing the API with Postman, I encountered an error stating "data must be a string or Buffer and salt must either be a salt string or a number of rounds". Here is my code: const router = require('exp ...

Ways to eliminate duplicate objects from an array using Angular 6

I'm having trouble removing duplicate value objects in an array and it's not working as expected. I believe the duplicate function is functioning correctly, but the changes are not being reflected in the li list. Can you pinpoint where I need to ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...