Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single request.

Currently, my approach involves:

  // within custom ctx.ts

import { AsyncLocalStorage } from "node:async_hooks";

export const asyncLocalStorage = new AsyncLocalStorage<string>();

export const createContext = (fn: any): any => {
  const trace = "hardcoded-trace (could be a new UUID)";
  return asyncLocalStorage.run(trace, fn);
};

export const getTrace = () => {
  return asyncLocalStorage.getStore();
};
  // in server.ts

  const remixHandler = createRequestHandler({
          build: initialBuild,
          mode: initialBuild.mode,
        });

  app.use((req, res, next) => createContext(next));
  app.use((req, res, next) => {
    // accessing hardcoded trace value here in a following middleware
    console.log(getTrace());
  });
  app.all("*", remixHandler);
// in a Remix loader

export const loader = async ({ request }: LoaderFunctionArgs) => {
  // unable to access Trace in the loader (seemingly out of context?)
  console.log(getTrace());
};

It seems like the async context gets lost when Express transitions to Remix. Exploring further into this without diving deep into Remix's internal workings is not straightforward.

The only potential solution I see is passing the context through getLoadContext within createRequestHandler. This would involve creating separate async contexts in the loader function, action function, etc., which might feel like a convoluted implementation. Essentially, multiple contexts need to be created and managed for a single request (Express, loader, action...).

My inquiry is: how can I establish a unified async context accessible throughout Express middleware, Remix action, Remix loader, etc., ensuring a consistent context from the start to end of an Express request?

Answer №1

Although I have yet to test it out myself, according to the documentation on their express adapter, the recommended approach is to utilize the getLoadContext function from createRequestHandler in order to seamlessly connect Remix with your server.

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

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

When executing `npm install` within a Docker container, the error message `cb() never called!` may be encountered

My project has a rather small package.json file: { "name": "chilldev-web", "version": "2.1.0-SNAPSHOT", "description": "Client-side build tool for a project.", "license": "UNLICENSED", "private": true, "dependencies": { "in ...

What is the best way to extract specific values from an array?

Is there a way to extract specific values from an array? module.exports.getAll = async function (req, res) { try { const cards = await Card.find({}) res.status(200).json(cards) } catch (e) { errorHandler(res, e) } } Cur ...

Creating a subtype in typescript involves specifying values for certain fields and getting rid of any optional members in the type definition

interface Person{ name:string, age:number, gender?:string } interface Employee extends Person{ name='John Doe', age:number } I am trying to achieve the above structure for a person and employee in TypeScript. I am also curious if something simi ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

What is the process by which Nginx manages outbound requests sent from Node.js as a client?

Introduction: I currently have an angular frontend and a node backend (Server A) that are functioning properly. Nginx is also being utilized for Server A. Now, I need to make an API call from my Node server (Server A) to an endpoint on another server (Serv ...

CORS policy causing Socket.io communication issues in a Node.js and Angular app

I have a node.js server running with express and socket.io. When I try to communicate with a simple JavaScript client, everything works fine. However, when I attempt to establish communication with an Angular app (using ngx-socket-io), I encounter the foll ...

If you're setting up a new Next.js and Tailwind CSS application, you can use the flags -e or --example to start the project as a

After several attempts at creating a Next.js app with Tailwind CSS using JavaScript, I keep getting TypeScript files. How can I prevent this error? Despite following the usual commands for setting up a Next.js project, I am consistently ending up with Typ ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

The child object in Typescript is characterized by its strong typing system

Looking to convert plain AngularJS code to Typescript? Take a look at this example: app.someController = function ($scope) { // var $scope.Data = null; var $scope.Data: SomeCollection = null; I need to associate Data with scope and specify it as type ...

Protecting Paths in Express and Node.js

I am searching for the most effective method to "restrict" specific routes. Here's an example to illustrate what I mean: Let's say we have two users: -user1 with id: 123 -user2 with id: 456 Client Side (Angular): //LOGGED IN AS USER 123 $ht ...

The hot loader is replicating code multiple times instead of conducting hot swapping

Every time I make a change in a component, webpack recompiles and React hot swaps the module over. However, I've noticed that my code runs multiple times after each hot module swapping occurrence. For example, if I make a change once, the functions ru ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Sharing Pictures (Using Express, Node, and MongoDB)

Seeking advice on the best method to create an upload feature for a web gallery application. After researching, I've come across different approaches like storing image data in Mongo: https://gist.github.com/aheckmann/2408370 Alternatively, saving ...

Unleashing the power of Angular 7+: Extracting data from a JSON array

As a newcomer to Angular and API integration, I am facing a challenge in fetching currency exchange rates data from the NBP Web API. The JSON file structure that I'm working with looks like: https://i.stack.imgur.com/kO0Cr.png After successfully ret ...

What is the best way to retrieve data from this Schema?

Could you please assist me in navigating my data from this array? I have successfully fetched and stored it in state. While I can view it on Postman, I am encountering difficulties displaying it on my frontend when using .map(). Could you provide guidance ...

Issue with setting context.cookies in Deno oak v10.5.1 not resolved

When I try to set cookies in oak, the cookies property of the context doesn't seem to update and always returns undefined. This happens even when following the example provided in their documentation. app.use(async ctx => { try { const ...

Providing static files in Express while utilizing mustache templates

I'm struggling to configure Express to serve a directory of static mustache files. I have an object with data like this: { a: 'Hello :)' b: 'Goodbye :(' } Along with two files: public/a.html <div>{{a}}</div> pu ...

Next.js: 404 Error Occurs When Accessing Images Post-Build

The standard URL structure is http://localhost:5000/_next/image?url="someURL". I'd like the URL format to be http://localhost:5000/demo/_next/image?url="someURL". This can be achieved using the following code snippet: // next.con ...

Determine the size of the resulting zip file with NodeJs

I am currently utilizing NodeJs (expressJs) along with the archiver module to stream a zip file directly to the client without storing the final ZIP file on the server (streaming zip serving). However, one issue I am facing is that I am unable to retrieve ...