'Is there a 404 errorcode fallback page for svelte-routing?
This fallback component={NotFound} is the only way i found for error pages but returns a component page with server code 200, i'd like to get code 404.
Is there a way Not using sveltekit ?
import { Router, Link, Route } from "svelte-routing";
import NotFound from "./components/NotFound.svelte";
...
<Route path="/">
Welcome <hr />
<Login {toast}/>
</Route>
<Route component={NotFound} />
</Router>
Solution 1:[1]
svelte-routing
is a component-based router and as such it has no control over your server, so it can't manipulate the response in any way other than picking the right component for you. You can still return different status codes, but you need to do it manually server-side.
If you're using static file hosting, I don't think there's a way to do it other than listing all your valid routes in your platform's configuration so that it can return 200 on valid routes and 404 otherwise. The route duplication is unfortunate but it's likely unavoidable.
However, if you're server-side rendering your app, you can communicate with your components in order to respond with the right status code. In your request handler, create a context object to hold your data:
import App from './App.svelte';
import { generatePage } from './page-template.js';
function handler(request, response) {
const SSR_RESPONSE = { statusCode: 200 };
const renderedApp = App.render(
{ url: req.url },
{ context: new Map([['SSR_RESPONSE', SSR_RESPONSE]]) }
);
response.statusCode = SSR_RESPONSE.statusCode;
response.end(generatePage(renderedApp));
}
You can now read and write to this object from your components:
<!-- NotFound.svelte -->
<script>
import { getContext } from 'svelte';
getContext('SSR_RESPONSE').statusCode = 404;
</script>
<h1>Not found</h1>
This technique can be used not only for status codes but for headers, conditional templating, or whatever else you can think of.
Note that in order for this to work, you must set your context values during component initialization (ie. not in callbacks, in asynchronous contexts, setTimeout
s, etc). This is required because SSR happens synchronously, so by the time you update the context asynchronously, your response will have already been sent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |