preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.02k stars 155 forks source link

Sending 404 status code when the routes don't match #402

Open sidvenu opened 3 years ago

sidvenu commented 3 years ago

Right now I observe preact-router sends 200 status code when no routes match. React Router has a status prop that handles it (ref: https://stackoverflow.com/questions/36052604/how-to-let-react-router-respond-with-404-status-code).

Is there a way to do this with preact-router?

developit commented 2 years ago

I believe this can be achieved via the following:

import { createContext } from 'preact';
import { useContext } from 'preact/hooks';

const HttpStatus = createContext({ code: 200 });

function NotFound() {
  const status = useContext(HttpStatus);
  status.code = 404;
  return <h1>Not found</h1>;
}

server.use((req, res, next) => {
  const status = { code: 200 };
  const html = renderToString(
    <HttpStatus.Provider value={status}>
      <App />
    </HttpStatus.Provider>
  );
  res.writeHead(status.code);
  res.end(html);
});
jasonhilldm commented 2 years ago

I have created a preact app using "npx preact-cli create typescript XXX" and am trying to return a 404 status code for routes that don't match. I am not sure where to place the code provided above though...do I need to add a new file to the scaffolded app or is there an existing file that I should edit?