When working in a Node.js environment, especially with TypeScript, you might come across situations where you need a simple caching mechanism — something lightweight to store a variable that stays alive as long as the server is running.
One of the most efficient and straightforward ways to achieve this is by using globalThis and declare global.
Let me walk you through how and why I used this approach in a real-world scenario, and break down the concepts from start to finish.
The Problem I Faced
In one of my projects, I was managing bookings for workshops. Each booking record included a vehicle_id, which pointed to a vehicle stored in another system.
We had a third-party system that needed to fetch booking data along with vehicle details in the same API call.
To support this, I created a hook in Directus that runs before every bookings fetch operation. This hook was responsible for:
Detecting if the vehicle_id exists.
Fetching the full vehicle data from the external system.
Attaching the vehicle object to the booking result.
The Real Challenge: Avoiding Duplicate API Calls
I didn’t want to fetch the same vehicle data multiple times, especially since vehicle data doesn't change frequently. That would waste time and network resources.
So I needed a simple caching layer to store the vehicle data after the first fetch, and reuse it for future requests — as long as the server is still running.
What is globalThis?
In JavaScript (and TypeScript), globalThis is an object that gives you access to the global scope, no matter the environment (Node.js, browser, etc).
That means any variable you attach to globalThis will be accessible from anywhere in your code, and will live as long as the server process is running.
Example:
globalThis.myAppName = "DriveMotive"; console.log(globalThis.myAppName); // Output: DriveMotive
Using globalThis with TypeScript
In a TypeScript project, if you try to write:
globalThis.__vehicleCache = new Map();
You’ll get a TypeScript error:
❌ Property '__vehicleCache' does not exist on type 'typeof globalThis'.
That’s because TypeScript is type-safe and doesn’t know about this property unless you explicitly tell it.
How to Declare a Global Variable in TypeScript
Step 1: Let TypeScript know this is a module
At the top of the file (usually types.d.ts), add:
export {}; // This makes the file a module
Step 2: Declare the global variable
declare global { var __vehicleCache: Map | undefined; }
This tells TypeScript:
"Hey, there is a global variable called __vehicleCache, and it's either a Map or undefined."
Step 3: Initialize the Cache
In your actual logic, you need to initialize the cache if it's not already created:
const vehicleCache = (globalThis.__vehicleCache ??= new Map());
This single line does three things:
Checks if __vehicleCache already exists in globalThis
If yes, assigns it to vehicleCache
If not, creates a new Map() and assigns it
I Hope This Post was Helpful, See you in the Next One.
Top comments (0)