Sending 404 status code when the routes don't match
sidvenu opened this issue · 2 comments
sidvenu commented
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
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
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?