Thursday 20 February 2020

Configuring NGINX for SSR React with Node and Express with routing

I need some help configuring NGINX. Currently I am able to hit / on the browser and get the website loaded up. But then I get a 404 page from nginx when I hit it with any subroutes, e.g. /login. I have node serving all the endpoints, app.get('/*', (req, res) => {... return res.send("")}I'm handling the routes using react-router-dom and react-router-config. I'm also handling errors and reroutes in express node:app.get('/*', (req, res) => { // SSR stuff if (context.url) { return res.redirect(301, context.url); } if (context.status === 404) { res.status(404); } const { helmet } = helmetContext; return res.send( ` // more html... `, ); } This is a portion of my nginx.conf:server { listen 80; listen [::]:80; server_name 18.223.162.221; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:3000; try_files $uri $uri/ =404; } # error_page 404 /404.html; # location = /40x.html { # } # error_page 500 502 503 504 /50x.html; # location = /50.xhtml { # } } When both of the blocks error_page 404 and error_page 500 are uncommented, the sub route, e.g. /login seems to make node to capture the last endpoint in the routes array, displaying the Notfoundpage, despite that the route should've displayed the Loginpage. export const routes = [ { path: '/', exact: true, render: Homepage, }, { path: '/login', exact: true, render: Loginpage, }, { path: '/protected', exact: true, render: PrivateRoute, }, { component: Notfoundpage, } ]; Commenting both of the error_page blocks in the nginx.conf load the nginx's 404 Not Found page when hitting the browser with /login. The same can be said when only uncommenting the error_page 500 502... block.I just need to be able to render all those pages at those routes, and the Notfoundpage at any unknown routes. What am I missing in the nginx.conf? Or where else should I be looking at?

Submitted February 21, 2020 at 04:40AM by jsphkm

No comments:

Post a Comment