Question about Server-Side Routing with React

I’m looking to get started setting up my server for the Nightlife Coordination app. I’m just wondering how I would differentiate my page routes from my API routes. I was reading a tutorial about universal routing with React and it mentioned using a catch-all route ("*") that would intercept all requests and match it to a route specified with React on the front end. But if I do that, where would I handle an API request? Say, for example, I wanted to get some data from a database with a GET request. Should I create another instance of express on the server? I’m a bit confused with this one.

Hi @codefu-chivy

If you think about an express application as a series of if else statements it might help understand the catch-all a bit better.

So say you had the following application:

// if
app.get('/api/pubs', function(req, res) {...})

// if else
app.post('/api/pubs/add', function(req, res) {...})

// else
app.get('*', function(req, res) {/* Do rendering stuff here */})

Express will go through each declared route in order and execute the function if the url matched the specified route. If it gets to '*' it will execute ALWAYS because it is the catch-all wildcard route, which is why we have it at the bottom of the declared routes. If we didn’t specific the catch-all and no routes match, we would get a 404 not found.

With this structure we can have both the API functionality and server rendering functionality in one express application.

Ultimately, Reacts server rendering is just creating a string of HTML from your React application that you can send back to the client instead of serving a static HTML file.

When you say front-end route, I assume you’re talking about using something like React-Router? In which case, the process is fairly similar, you just add additional logic to the rendering function, this page may help for pre v4 react-router: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ServerRendering.md.

1 Like

Thanks for the reply! And that pretty much cleared up everything. I had a similar problem with the voting app, where I handled every route with react router, so an actual request to the server with that route (a page refresh for example) would throw a “page not found”…big problem. So I know how to fix that now as well.

1 Like