Search code examples
node.jsexpressfetch

Can I make a fetch request from an express request handler or middleware?


Let's say I have an express api with an /api/load-post endpoint. That is handled by the loadPostHandler: RequestHandler

index.ts

const app = express();
app.get("/api/load-post", loadPostHandler);

loadPostHandler.ts

Can I make a fetch request from that handler?

import fetch from "cross-fetch";

export const loadPostHandler: RequestHandler = async (req, res) => {

  // HANDLE BLOGPOST LOAD

  res.json({ blogPost: blogPostData })               // RES JSON THE BLOGPOST DATA

  await fetch("/api/updateViewcount?id=POST_ID");    // MAKE A FETCH REQUEST

};

Is this something people usually do? Or is this an anti-pattern? Not sure if this would even work.


Solution

  • Short answer

    Yes, you can make requests in the api call handler in general, and it depends on the requirements of that api.

    Longer version

    Judging by your example: you want to update view count, and since there is no use of response of it, you don't need to await for the response. You can just fire it without await. And structurally it would be better practice to move it to a separate function that make an actual call, or fire an event and handle it in a different place. Moreover, it looks like you are calling the same api server, in that case it will be better just to call a function instead of the api call.

    const updatePostViewcount = postId => {
        // HANDLE BLOGPOST VIEWCOUNT UPDATE
    }
    
    export const loadPostHandler: RequestHandler = async (req, res) => {
    
      // HANDLE BLOGPOST LOAD
    
      // no await here because we don't need the response
      // it will still run asynchronously
      updatePostViewcount(POST_ID);
      res.json({ blogPost: blogPostData }) // RES JSON THE BLOGPOST DATA
    };