Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Practical Astro
Lesson Plan
  1. Content Systems
    1. Introduction
    2. An import alias
    3. Using Markdown
    4. Markdown extended
    5. Markdown component
    6. Markdown component in frameworks
    7. Content collections made easy
    8. Basic blogs
    9. Blogs made easy
    10. Prev/Next navigation
    11. Pagination made easy
    12. Better tag pages
    13. Paginated tag pages
    14. Markdown layouts
    15. Partials
    16. JS over JSON Data
    17. Dynamic 404 pages
    18. Putting everything together
    19. Other useful systems
  2. Image Systems
    1. Introduction
    2. Images are complicated because of this
    3. Astro's Image component
    4. Astro's Picture component
    5. Improvements over Astro's Image and Picture Components
    6. Images in Markdown and MDX
    7. Images in framework components
    8. Background images
    9. Art Direction with Astro
    10. Videos without layout shifts
    11. GIF Replacements and background video
    12. SVGs and icons
    13. SVG backgrounds
    14. Adding noise to images
    15. Asset caching on GitHub Actions
    16. Putting everything together
    17. Other useful systems

Dynamic 404 pages

1m:18s

Most 404 pages are simple. You create a 404.mdx or 404.astro and call it a day.

But if you ever need to show different 404 content based on different conditions, you need a dynamic 404 page.

This is rare, but let me show you an example.

For Splendid Labz, I wanted to design the 404 page such that:

  • If they are not in the documentation section, the 404 will be a full-screen design. (Example)
  • If the user is in a documentation section, then the 404 should showcase their library and adopt the theme color for that library. (Example)
404 on most pages
404 in documentation

The difference here is in the layout of the file.

Creating a dynamic 404

To create a dynamic 404, we can use a [...catchall] page. This page needs to be server-rendered.

[...catchall].astro
---
export const prerender = false
---

We can then get the pathname of this 404 page with Astro.url.

Then, in this case, if the pathname starts with docs, I link it to a specific layout. If the path name does not start with docs, I link it to another layout.

---
import { If } from '@splendidlabz/astro'
import Docs from '@/layouts/Docs.astro'
import Landing from '@/layouts/Landing.astro'
import NotFound from '@/components/NotFound.astro'
export const prerender = false
const { pathname } = Astro.url
const isDocs = pathname.startsWith('/docs')
---
<If condition={IsDocs}>
<Docs {...props}><NotFound {...props} /></Docs>
</If>
<If condition={!IsDocs}>
<Landing {...props}><NotFound {...props} /></Landing>
</If>

That’s it! It’s very simple :)