#Proper way of redirecting to 404 page when slug is invalid in SSR Dynamic Routing

1 messages · Page 1 of 1 (latest)

frosty geyser
chrome wigeonBOT
#

Hi @frosty geyser. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, when you're using Server-Side Rendering (SSR) with dynamic routing, you can redirect to a 404 page when a slug is not found or invalid. However, the method you've provided is not the recommended way in Astro. Instead, you should use Astro.redirect('/404').

Here's an example of how you can do this:

---const { slug } = Astro.params;
const page = pages.find((page) => page.slug === slug);
if (!page) return Astro.redirect("/404");
const { title, text } = page;---

In this example, we're fetching a page based on the slug parameter. If the page is not found (i.e., page is undefined), we redirect to the 404 page.

Remember to create a 404 page in your src/pages directory. Here's an example of a simple 404 page:

<html lang="en">  
  <head>    
    <title>Not found</title>  
  </head>  
  <body>    
    <p>Sorry, this page does not exist.</p>  
  </body>
</html>

This way, if the slug is not found, the user will be redirected to this 404 page.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: