I see the issue now. You're trying to use Astro.rewrite("/404") inside a component rather than at the page level, which is causing the error.
Just like with Astro.redirect(), the Astro.rewrite() function can only be used at the page level, not within components. This is because both functions modify response headers, which can only be done before the headers are sent to the browser.
According to the documentation:
Features that modify the Response headers are only available at the page level. (You can't use them inside of components, including layout components.) By the time Astro runs your component code, it has already sent the Response headers and they cannot be modified.
HTML streaming
How to fix this:
Move your rewrite logic to the page level (in your .astro file in the src/pages directory). For example:
---
// In your [slug].astro or other page file
// Check your condition here
if (someCondition) {
return Astro.rewrite("/404");
}
---
<!-- Rest of your page content -->
If you need to handle 404 cases in a component, you should pass that information back to the parent page component and let the page handle the rewrite.
For example, your component could return a status or flag:
---
// In your component
const isNotFound = checkSomething();
---
{isNotFound && <p>Not found!</p>}
Then in your page:
---
import MyComponent from '../components/MyComponent.astro';
const componentResult = await someCheckFunction();
if (componentResult.notFound) {
return Astro.rewrite("/404");
}
---
<MyComponent />
This approach ensures that the rewrite happens at the page level where it's allowed to modify response headers.
Let me know if you need more specific guidance based on your implementation!