0
0
AstroHow-ToBeginner ยท 3 min read

How to Use getEntry in Astro: Syntax and Examples

In Astro, getEntry is used to fetch a single content entry by its slug or ID from a collection. You call getEntry(collection, slug) inside your Astro component or server code to retrieve the entry data for rendering or processing.
๐Ÿ“

Syntax

The getEntry function requires two arguments: the collection name (a string identifying your content group) and the entry slug (a string identifying the specific content item). It returns a Promise resolving to the content entry object or null if not found.

Use it like this:

  • getEntry('collectionName', 'entrySlug')
javascript
import { getEntry } from 'astro:content';

const entry = await getEntry('blog', 'my-first-post');
๐Ÿ’ป

Example

This example shows how to fetch a blog post entry by its slug and display its title and content inside an Astro component.

astro
---
import { getEntry } from 'astro:content';

const post = await getEntry('blog', 'welcome-post');
---

<article>
  <h1>{post.data.title}</h1>
  <p>{post.body}</p>
</article>
Output
<article> <h1>Welcome to My Blog</h1> <p>This is the first post content.</p> </article>
โš ๏ธ

Common Pitfalls

Common mistakes when using getEntry include:

  • Using the wrong collection name or slug, which returns null.
  • Not awaiting the Promise, causing undefined data.
  • Trying to use getEntry in client-side code instead of server-side or Astro components.

Always verify your collection and slug names match your content files exactly.

javascript
/* Wrong: missing await, will cause errors */
const post = getEntry('blog', 'welcome-post');

/* Correct: await the Promise */
const post = await getEntry('blog', 'welcome-post');
๐Ÿ“Š

Quick Reference

  • getEntry(collection, slug): Fetch one content entry by slug.
  • Returns a Promise resolving to the entry object or null if not found.
  • Use inside Astro server code or components only.
  • Collection and slug are case-sensitive strings.
โœ…

Key Takeaways

Always await getEntry to get the content entry data.
Use exact collection and slug names matching your content files.
getEntry works only in server-side or Astro component code, not in client scripts.
It returns null if the entry is not found, so check for that.
Use getEntry to fetch a single content item for rendering or processing.