Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sidvenu opened this issue Aug 21, 2021 · 2 comments
Open

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

sidvenu opened this issue Aug 21, 2021 · 2 comments

Comments

@sidvenu
Copy link

sidvenu commented Aug 21, 2021

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
Copy link
Member

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
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants