Closed reintroducing closed 5 years ago
Usually you want your server side routing to be the same as your client side routing so you'd use something like react router instead of express routes.
Having said that there's nothing preventing you from exporting an express router which itself is a middleware function, e.g.
export default () => {
const router = Router();
router.use(cookieParser())
router.get("/version”, () => {})
return router;
}
@richardscarrott Sorry I should have been more clear. My FE routes are indeed matching, I was referring more to BE routes. For instance, we added a health check endpoint for the node server, and I am having to compare the url from the request to decide whether i should be sending back the HTML (in the case of someone hitting the site to display the client code) or just sending a 200 response to the health check. ultimately i suppose my question is whether i can somehow get access to app
so i can add other items to it. I hope I'm making sense but again, this could also be my misunderstanding of node itself.
As for exporting the router, where would you put that code?
The router would be returned from your server renderer function, e.g.
export default function serverRenderer() {
const router = Router();
router.use(
(req, res, next) => {
res.status(200).send(`
<!doctype html>
<html>
<head>
<title>App</title>
</head>
<body>
<div id="root">
${renderToString(<App />)}
</div>
<script src="/client.js"></script>
</body>
</html>
`)
});
return router;
}
However, for any routes unrelated to server side rendering such as a healthcheck (usually any code that doesn't need to be compiled with webpack) you can just mount them in your main app before you mount the server renderer.
i havent tested your code but i don't think that would work as the return from serverRenderer needs to be the (req, res, next) => {
portion. I've gotten errors in the past that specifically say the method signature needs to be this.
It will as a Router is just a middleware function, I'm using it that way in a project currently.
good to know, thanks for your help. i don't have an immediate need to do this right now, it was more of a theoretical question for when the need arises, so i'll try it when that happens. i'll close the issue for now, thank you.
The example in the README for the server renderer is basically a catch-all route:
return (req, res, next) => {
. What if you want to have multiple routes react differently? Do you have to check for the request url and a bunch of if/else statements? Or is there access toapp
somewhere that allows you to add otherapp.use
statements for different routes (or other things, like adding middleware for example)?Hopefully what I'm asking is clear enough to understand. I'm a node newb so pardon my ignorance.