Node.js — Strict Type for Request Headers with TypeScript

Using TypeScript comes with the benefit of having your IDE or editor type-check everything in your project. Another benefit is that you get IntelliSense in all places where it’s possible. But you don’t get IntelliSense when working with Node.js request headers. We can change that by creating our own, strict type for HTTP request headers.

This tutorial shows you how to tighten the types for Node.js request headers to support IntelliSense during development and compile time.

Node.js Series Overview

  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js
  27. Check if a String is Empty in JavaScript or Node.js
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js
  29. Left-Trim Characters Off a String in JavaScript or Node.js
  30. Right-Trim Characters Off a String in JavaScript or Node.js
  31. Lowercase the First Character of a String in JavaScript or Node.js
  32. Uppercase the First Character of a String in JavaScript or Node.js
  33. Prepend Characters or Words to a String in JavaScript or Node.js
  34. Check if a String is a Number
  35. Convert a String to Buffer
  36. Prevent Line Breaks in String Template Literals

The Default Types for HTTP Request Headers in Node.js

The types for IncomingHttpHeaders in Node.js (at least version 20) provide a list of common headers. Also, that type extends a dictionary. The Node.js dictionary type is an index signature to open up a type for any key-value pair that is not known upfront:

interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {  
    accept?: string | undefined;
    "accept-language"?: string | undefined;
    …
    vary?: string | undefined;
    "www-authenticate"?: string | undefined;
}

interface Dict<T> {  
    [key: string]: T | undefined;
}

The problem with this type definition is that
- the index signature throws type narrowing and IntelliSense out the window - you can’t use IntelliSense for the HTTP request header keys

Typed Request Headers in Node.js

We want to conceal the type for Node.js HTTP request headers to the list of known keys. Also, we want to provide a way for developers to extend the concealed, typed list of request headers so that IntelliSense provides the extended values, too.

You can achieve that by creating a new type for the HTTP request headers.

First, remove the index signature from the IncomingHttpHeaders interface. You can remove the index signature using key re-mapping. We have a dedicated tutorial on removing the index signature from TypeScript types here on Future Studio:

import { IncomingHttpHeaders } from 'node:http2'

export type RemoveIndexSignature<T> = {  
  [K in keyof T as string extends K
    ? never
    : number extends K
      ? never
      : symbol extends K
        ? never
        : K
  ]: T[K];
}


/**
 * This type copies over all properties from the `IncomingHttpHeaders` type
 * except the index signature. The index signature is nice to use custom
 * HTTP headers, but it throws away IntelliSense which we want to keep.
 */
export type HttpDefaultRequestHeaders = RemoveIndexSignature<IncomingHttpHeaders>  

Your created HttpDefaultRequestHeaders type contains all request headers. You can access each header by its name. Here’s a preview in Visual Studio code when using a property with type keyof HttpDefaultRequestHeaders:

Strict TypeScript type for HTTP Request headers

Create an Extendable HTTP Request Headers Interface

You created a strict type for request headers in the previous section. The created type contains a set of common HTTP header keys and provides strict typing in your project. But you can use any HTTP request header that’s not part of your type. For example, there’s no request header for rate limiting like X-Rate-Limit.

You can solve this problem too by creating an extendable TypeScript type. Extendable types are interfaces because they support declaration merging.

Create an interface for HTTP request headers that extends the previously created, strict type. You may also add your custom request headers already. Here’s a HttpRequestHeaders interface that you can use in your project:

/**
 * This `HttpRequestHeaders` interface can be used to extend the default
 * HTTP headers with custom header key-value pairs. The HTTP request
 * picks up the custom headers and keeps IntelliSense for the dev.
 */
export interface HttpRequestHeaders extends HttpDefaultRequestHeaders {  
  'X-Rate-Limit': string | undefined
}

Use the HttpRequestHeaders interface in your code when you’re accessing HTTP request headers:

Extendable HTTP Request Headers Interface

Awesome!

The Supercharge Node.js Framework

This tutorial resulted from our pains with HTTP request headers while developing the Supercharge Node.js framework. We wanted strict types for request headers and also allow developers to extend that list.

The Supercharge framework uses this approach of providing strictly typed HTTP request headers. It creates a pleasant developer experience and you can freely extend the list of available headers. You should have a look 🙂

Enjoy strictly typed HTTP request headers in Node.js!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.