The 'authorization' property is not available on the 'Request' object

Here is a code snippet to consider:

  setContext(async (req, { headers }) => {
    const token = await getToken(config.resources.gatewayApi.scopes)

    const completeHeader = {
      headers: {
        ...headers,
        authorization:
          token && token.accessToken ? `Bearer ${token.accessToken}` : '',
      } as Express.Request,
    }

    console.log('accessToken: ', completeHeader.headers.authorization)
    return completeHeader
  })

An issue arises with the following TS error message:

Property 'authorization' does not exist on type 'Request'.

The error occurs when trying to retrieve

completeHeader.headers.authorization
. This property authorization is not part of the Express.request interface. It seems odd that TypeScript cannot infer the correct type from the literal object, which is clearly a string. Without explicitly setting the type to as Express.Request, an unsafe any assignment error is thrown.

Do we need to create a new TS interface just for this single field? Or are we utilizing an incorrect type definition? The authorization field appears to be commonly used for transmitting tokens.

Answer №1

Coercing completeHeader.headers into the Express.Request type is causing this issue. The coerced type takes precedence over the inferred type.

To resolve this, you can expand the coerced type using the following syntax:

as Express.Request & { authorization: string }

Alternatively, you could define a completely new type like so:

type AuthorizedRequest = Express.Request & { authorization: string };
...
as AuthorizedRequest 

Answer №2

When I encountered an issue where I needed to add a user but received an error in the headers with authorization(req.headers.authorization), my solution was as follows:

Scenario 1: 1.1. The error pointed to req.headers.authorization, which reminded me of a similar error I had encountered with the user object:

import { IAuthRequest } from "./../types/user.type";

const checkAuth =
    () => async (req: IAuthRequest, res: Response, next: NextFunction) => {
        try {
            //2. The main problem surfaced here
            //To resolve the issue with 'req.user', 
            //I assigned <req:IRequestUser>
            if (!req.headers.authorization) throw new Error("Please log in");

            const token = req.headers.authorization.split(" ")[1];

            if (!process.env.SECRET_ACCESS_TOKEN)
                throw new Error("Please create <SECRET_ACCESS_TOKEN> in .env file");

            const { decoded, expired } = Jwt.verifyJwtToken(
                token,
                process.env.SECRET_ACCESS_TOKEN
            );

            if (expired) return res.status(401).send("Token has been expired");

            //Resolving errors by changing from <req: Request> to <req: IAuthRequest>
            req.user = decoded;

            next();
        } catch (err) {
            return res.status(400).send(err);
        }
    };

1.2. In a folder named "types", I created a file called <user.type.ts> and added:

export interface IUserData {
    _id: string;
    email: string;
    username: string;
}

export interface IRequestUser extends Request {
    user: IUserData;
}

export type IAuthRequest = IRequestUser & {
    headers: { authorization: string };
};

To make the above code work correctly, simply remove the comments for better readability and comprehension.

Scenario 2: Later, I discovered an even simpler solution:

import { IAuthRequest } from "./../types/user.type";

const checkAuth =
    () => async (req: Request, res: Response, next: NextFunction) => {
        try {
            req as IAuthRequest;

            //your code...

            next();
        } catch (err) {
            return res.status(400).send(err);
        }
    };

Hopefully, this can be beneficial to someone facing a similar challenge.

Answer №3

const jwt = require('jsonwebtoken');
const { NextFunction, Request } = require('express');
try{
    const authorizationHeader = req.headers.authorization;
    // Here you can add logic to decrypt the token and check for an empty authorization header
}

Simply importing Request from express will allow access to the authorization property on the request headers.

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

Can Restify Node return an integer value?

https://i.stack.imgur.com/72ltz.png I recently encountered an issue while trying to validate my URL with Facebook for my bot. It appears to be related to a data type problem since I seem to be sending a string instead of an integer. Below is a snippet of ...

JavaScript library for creating animated car movements on a map using JPG images

Looking for a way to animate a car's movement on a map? I have a map image in jpg format (not svg) and a sequence of (x,y) points ready to go! If you could recommend a JavaScript library that can help me easily create an HTML page with this animation ...

Choose multiple children and grandchildren by checking the root checkbox multiple times

jquery/javascript $('.ic_parent').change(function(){ var id = $(this).attr('value') while (id.length >0){ if ($(this).attr('checked')) { $('#update_ics_table').find('input:checkbox[id = "child- ...

Searching for data in MongoDB with multiple conditions using the Mongoose find

When I attempt to verify a verification code during user registration, the query has multiple conditions. If a document is returned, then the verification code is considered verified; otherwise, it is not. The issue with the following snippet is that it ...

Problem with using React state hook

Trying to implement the state hook for material-ui's onChange feature to manage error texts, I encountered an issue. I have included a screenshot of the error displayed in the console. https://i.sstatic.net/qjed8.png Below is the snippet of my code: ...

Prepare the column data for Vue Good-Table by formatting it beforehand

I've created a custom Vue.js component that retrieves orders from a Woocommerce store. These orders include product variations and are received in object form. Before displaying the data in a table, I need to format the object accordingly. This is a ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Encountered an issue while working with npm vue-cli

Operating System: Windows 10 Node Version: v8.9.2 NPM Version: 5.5.1 I successfully installed vue-cli using NPM, but encountered an error when trying to run 'npm run dev' command. Below is the error message: npm ERR! code ELIFECYCLE npm ERR! ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

Retrieving User Keypad Input with Twilio Phone Calling in a Node.js Application (excluding web server)

const userInput = message.content.split(' ') const phoneNumber = userInput[1] const messageToSay = userInput.slice(2).join(' ') if (phoneNumber) { // Dial phoneNumber and deliver messageToSay, then gather ke ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...

Is there a way to prevent a web page from refreshing automatically for a defined duration using programming techniques?

I am currently working on a specific mobile wireframe web page that includes a timer for users to answer a question after the web content body has loaded. There are two possible outcomes when answering the question: 1) If the user fails to answer in time, ...

Using JQuery to implement a date and time picker requires setting the default time based on the server's PHP settings

I have implemented a jQuery UI datetime picker in my project. As JavaScript runs on the client side, it collects date and time information from the user's machine. Below is the code snippet I am currently using: <script> // Function to set ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Displaying a Countdown in a Django Loop: A Step-by-Step

Hey there, I've got a Javascript countdown nested in a Django for loop that's causing some trouble by displaying multiple instances. Currently, only the first countdown works when I click on any of the start buttons. I'd like each button to ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

Discover a multitude of items simultaneously using mongoose

I am trying to find multiple objects in a mongo model with different properties simultaneously. model.find({uuid: 235q422462}, {uuid: 435q4235239}, function(err, objects){ if(err){ console.log(err) } else { console.log(objects) ...

What could be causing the error within the 'react-code-blocks' library?

Currently, I am involved in a project that utilizes Typescript and React. However, I have encountered an issue while working with the 'react-code-blocks' library. The structure of my container component is as follows: interface ICodeBlockProps { ...