Dynamic vs Static Routes in Astro

By Alex Johnson 2024-01-22 6 min read

Dynamic Route Details

File: /blog/[slug].astro (dynamic route)
URL Pattern: /blog/[any-slug-here]
Current slug: "dynamic-vs-static"
Note: This route handles all /blog/* URLs except /blog/create (static route has priority)
#astro #ssg #ssr #performance

Understanding when to use SSG vs SSR in your Astro applications.

Route Priority in Action

/blog/create Static Route

Goes to create.astro (blog creation form)

/blog/dynamic-vs-static Dynamic Route

Goes to [slug].astro (this page)

Dynamic Route Implementation

---
// File: /blog/[slug].astro
export const prerender = false; // SSR for dynamic content

const { slug } = Astro.params;

// In real app: query database/CMS
const post = await getPostBySlug(slug);

if (!post) {
  return Astro.redirect('/404');
}
---

<Layout title={post.title}>
  <h1>{post.title}</h1>
  <p>Slug: {slug}</p>
  <div>{post.content}</div>
</Layout>

Test Different Slugs

Try these URLs to see how the dynamic route handles different slugs: