Running NotFound on the server side

Is there a way to have server-side code handle the case when a URL doesn’t match an existing route (404 NotFound) and can send a server HTTP 301 redirect before rendering the frontend?

The full story: I’m building a simple short links/golink type service where user’s can register short names for longer URLs. For example, would redirect to a much longer URL, like a google doc.

In a perfect world, there would be a catch-all route which would look at the URL, see if the path matches a record in the DB and to the longer URL. If not, it would render the form to create a new short URL.

In an even more perfect world, the short name could include path sections. For example: This would likely break the default routing patterns.

Using the NotFound route seems like a natural fit, but it seems like it’s still run in the browser. Is there any way to ensure this happens on the server-side?

Right now today you could:

We may include a <Route> directive that redirects, but the redirect would be coming from the client, not the server, so it wouldn’t be a “real” 301. If you need a server 301 you need something like Netlify redirects or the equivalent on another JAMstack provider.

Unfortunately due to the way single page apps work you can’t really rely on the server being around and returning proper HTTP status codes. In order to get your app to start you have to get an index.html which will be a 200 OK, and that’s it, any other calls will be XHR.

Thanks for the response. This makes sense and seems reasonable.

Some single-page frameworks include server-side execution in the components. I did a POC of this with next.js by putting the server-side part in MyDocument.getInitialProps, but that felt pretty hacky. Ultimately, with that POC I went a similar route to your recommendation and put a simple layer in front of the next app.