choo icon indicating copy to clipboard operation
choo copied to clipboard

Server rendering 404 handling

Open callum opened this issue 10 years ago • 5 comments

I've recently adapted the server rendering example for my project and I noticed that 404s aren't sent with a 404 status code. This is probably so trivial that it doesn't actually matter that much, but I think it might be worth looking at.

What I'm wondering is whether there's a smart way to tell the server that the route being rendered through .toString() is a non-match, without clunky string checking or something like that.

Interested to hear any thoughts on this.

callum avatar Oct 01 '16 09:10 callum

Yeah I've thought about that, and didn't really think it mattered - what we're doing on server-render is expose a cached production mode where we already know all the paths so can render on the server if needed. Would that work for you?

yoshuawuyts avatar Oct 01 '16 11:10 yoshuawuyts

@callum does that answer your question?

yoshuawuyts avatar Oct 05 '16 13:10 yoshuawuyts

I'm not sure. Let me try to explain with an example:

const app = choo()
app.router('/404', route => [
  route('/404', () => html`<p>404 not found</p>`),
  route('/foo', () => html`<p>foo</p>`)
])
app.toString('/bar') // technically this is a 404, but how do we know?

It might be nice to be able to hook in to the routes given for your app. Imagine a server implementation like this:

http.createServer((req, res) => {
  if (app.match(req.url)) {
    res.statusCode = 200
  } else {
    res.statusCode = 404
  }
  res.end(app.toString(req.url, {}))
})

callum avatar Oct 05 '16 13:10 callum

Well, based on https://github.com/yoshuawuyts/choo/issues/264 we could perhaps extract the routes ahead of time, and then if a url doesn't match one of those routes set the statusCode to 404, and still pass it to choo - would that work? - it's what you're saying but without adding an extra method to choo itself :D

yoshuawuyts avatar Oct 05 '16 14:10 yoshuawuyts

I'm sure that would be fine. I'm not advocating a new method in choo, but it might be nice if routing was more loosely coupled with choo. Liking some of your suggestions in https://github.com/yoshuawuyts/choo/issues/264.

callum avatar Oct 05 '16 14:10 callum