Home > front end >  How to run middleware on each React page in express server
How to run middleware on each React page in express server

Time:12-28

I'm running an express server and if no other certain URLS aren't met, the user is redirected to the React App:

app.get("*", verify, (req, res) => {
  if (maintenance) {
    return res.sendFile("./maintenance.html", { root: __dirname });
  }

  return res.sendFile(
    path.resolve(__dirname, "../frontend/build", "index.html")
  );
});

This successfully runs the verify middleware needed to check if the user making the request is logged in, if not it redirects them to another service for them to login.

I would've thought that since all URLS that are being used are going through the whole web app is going through this express server, the verify middleware would've been executed no matter what page the user is on. However, this middleware is only executed upon either opening the site on a browser that hasn't been to the site yet (not cached) or if the user force refreshes the page.

I'm new to React and this has led me to believe that React loads the whole app, and upon each change of page (for example from /home to /profile) it doesn't change the url, just loads the portion of the app that's already loaded and so no matter what page the user is on, express will always see that the user is only on the root domain.

How would I get pass this without doing any of this logic on the frontend side. E.g. run the verify function before each page on the react app is loaded into view

CodePudding user response:

Since React is all client side rendering you will need to handle that middleware in your React router, not your Node router. On the frontend we call this "middleware" protected routes.

The overall point is, you will need to protect those routes on the frontend, as when you change a page in React, Node does not know about it (because React is client side rendered).

  • Related