Implementing Typescript for HTTP header typing

I find myself in a state of confusion regarding Typescript and its suggestions for type definitions. Currently, I am working on a Graphql API with Apollo Server and attempting to implement authorization using JWT via request headers (I am rewriting an existing API). To start, I am extracting the token from request headers like this:

const token: string = req.headers.authorization

However, this results in an error stating "type string | undefined is not assignable to type string", so I adjusted it to:

const token: string | undefined = req.headers.authorization

After making this change, I noticed that the original API attempts to retrieve the authorization property from either req.headers.authorization or req.headers.Authorization. Although I do not understand why, I decided to follow suit by trying:

const token: string | undefined = req.headers.authorization || req.headers.Authorization

This led to a new error message: "type string | string[] | undefined is not assignable to type string | undefined".

So, I made another adjustment:

const token: string | undefined | string[] = req.headers.authorization || req.headers.Authorization

Now, I have some questions:

  • Why do req.headers.authorization and req.headers.Authorization have different data types?
  • After searching online, I see that all tutorials on authorization use req.headers.authorization, but what about req.headers.Authorization?

Answer №1

1: The disparity in data types between req.headers.authorization and req.headers.Authorization

To uncover the reason behind this distinction, refer to the TypeScript definitions for node's http library found here.

The definition for req.headers.authorization is:

'authorization'?: string;

Being optional allows it to be undefined, otherwise, it's a string.

On the other hand, req.headers.Authorization does not have a specific definition listed, requiring reference to the type definition for req.headers:

interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
  ...other stuff
}

This indicates that any undefined strings fall under the category of undefined, string, or string[].

2: Utilizing req.headers.authorization over req.headers.Authorization based on HTTP specifications

HTTP headers are case-insensitive according to the spec. Express and related frameworks typically handle lowercase conversion automatically, making req.headers.authorization the preferred choice.

Bonus

When using apollo-server-lambda, where capitalization is retained, opt for event.headers.Authorization. This flexibility accommodates differences across ApolloServer implementations by allowing for handling of undefined | string | string[] types.

Unrelated Tip on Semantics

const token: string | undefined | string[] = req.headers.authorization || req.headers.Authorization

Note that technically, naming the variable token may not align with the standard format of the Authorization header (

Authorization: <type> <credentials>
). Consider parsing out the specific "token" part if needed, typically located after the word Bearer .

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

Showing container element only if certain condition is met but display the children in Angular 2+

I am looking to create a grid-style view for a list of Angular components, where I can display up to 4 components in each row. The question that comes close to what I need is the following: Angular 2 NgIf, dont render container element on condition but sh ...

Sending multiple POST requests at the same time, but not sending any if one of them fails

Is there a way to send 2 post requests simultaneously, but ensure that if one request fails, both requests are canceled? These two post requests are separate functions on the backend (i.e., two different endpoints). I've researched similar questions ...

Refreshing a Variable's Value in NODE.JS

After much struggle, I've come to the realization that I may have to seek help from the experts on 'StackOverflow' for this issue. Here is my code that continues to baffle me: var express = require('express'), fs = require(&ap ...

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

Is there a way to expand the color options of mui using Typescript?

I'm attempting to expand the color options provided by mui. While overriding primary, secondary, and other preset colors works smoothly, I'm struggling with creating a custom set of colors right after. Despite numerous examples available without ...

Every time I click on a single button, all the text inputs get updated simultaneously

One issue I encountered is with a component featuring increment and decrement buttons. These buttons are meant to interact with specific products, yet when clicked, all text inputs update simultaneously instead of just the intended one. COMPONENT HTML: &l ...

What is the process for displaying a webpage using Node.JS and hogan-express?

Need help rendering a page in node using a router to pass a value to the template engine? Here is an example of the code: var apiRouter = express.Router(); apiRouter.get('/myPosts', function(req, res){ userPostsModel.findOne({'profile ...

Utilize Jest to import HTML as a string for testing purposes

While using sveltekit, I encountered an issue where I couldn't use the files API to import HTML templates. To work around this problem, I decided to import the content of the document as a string by creating a module that imports it (as explained here ...

Having trouble configuring a basic express server to host a static JavaScript file

Struggling to set up a basic Express server with accompanying HTML and JS files. Despite multiple attempts, I can't get the JS file to properly load. index.js: const express = require("express"); const app = express(); const path = require ...

When in production, Express and NextJS do not allow origin for CORS

I'm using Express and need to configure my CORS settings dynamically. My express app is running on localhost 3001, while my Next.js app is on localhost 3000. // If in production environment, allow access for Vercel app. const allowedOrigin = process. ...

The React-widgets DateTimePicker is malfunctioning and displaying an error stating that it cannot assign to the type of 'Readonly<DateTimePickerProps>'

Hello there! I am a newcomer to TypeScript and I am facing difficulty in understanding an error. Any help regarding this will be greatly appreciated. I have tried searching for solutions online and even attempted changing the version, but I am unsure of wh ...

Attempting to use checkboxes and the useState hook to filter an array, the checkbox loses its checked status

Within my code, I have an array named reportsData, which needs to be filtered in order to generate checkboxes. Each checkbox should have a label based on the names from another array called emittersData. Here is how I've set it up: const [searchUser, ...

The findAll method is being provided with a response that includes [{'primaryKey':null}] by Sequelize

Following advice from a post, I am using ES6 classes to define my sequelize models. However, when attempting to fetch data from the table using a simple api call on express, I encounter an issue. The generated query is correct and produces the desired res ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

The response body contains the right number of objects in the array, however, they are all blank

I recently embarked on a Ts.ED project utilizing TypeORM and Swagger to interact with my database. I've set up a UserController.ts file and a UserService.ts file. Within the service file, there's an async function that retrieves all users from my ...

Retrieve data from an API using parameters

Recently delving into the realm of Express API, I find myself faced with a challenge. My goal is to extract data from MongoDB that meets specific criteria. Let's take a look at what my MongoDB documents contain: {value:"24", category: "low"}, {value: ...

The key is not applicable for indexing the type as expected

Here is the TS code I am working with: type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" }; type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple" ? "good" : TFruit["color"] extends "green" ? "good" : ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Can a number value in a JSON object be converted to a string?

In my application, I have defined an interface: export interface Channel { canal: string; name: number; status: string; temperature: number; setpoint: number; permission: boolean; percentOut: number; } [UPDATE] in the HTML file: <input ...

To access the value of a DOM input in an Angular component, utilize the "renderer/renderer2" method

Recently, I embarked on my journey to learn Angular. One of my goals is to retrieve data from a form and store it in a database (Firebase) using angularfire2. While going through the documentation, I noticed that there is a "setValue()" method available b ...