Tillitsdone
down Scroll to discover

How to Fetch Data from Strapi API in AstroJS

Learn how to integrate Strapi with AstroJS for dynamic content management.

This guide covers API setup, data fetching, image handling, and best practices for building fast websites.
thumbnail

A majestic mountain range with fresh powder snow under clear skies capturing the pristine wilderness. Color palette: Light blue and cobalt with bright white snow peaks. Camera angle: Wide landscape shot from slightly elevated position ultra-realistic cinematic 8K UHD high resolution sharp and detail

Have you ever wondered how to create a blazing-fast website using AstroJS while managing your content with Strapi? You’re in the right place! Today, we’ll explore how to fetch data from a Strapi API in your AstroJS project, making your content management a breeze.

Setting Up Your Environment

Before we dive in, make sure you have both AstroJS and Strapi projects up and running. If you’re starting from scratch, you can create a new AstroJS project using:

Terminal window
npm create astro@latest

Creating the API Connection

First, let’s set up our environment variables. Create a .env file in your AstroJS project root:

PUBLIC_STRAPI_URL=http://localhost:1337

Abstract fluid shapes flowing seamlessly together representing data flow and connectivity. Color palette: Baby blue salmon-orange and ruby red with dynamic movement. Camera angle: Top-down view capturing the entire composition high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Fetching Data from Strapi

Let’s create a utility function to handle our API calls. Create a new file called lib/strapi.js:

export async function fetchApi(endpoint) {
try {
const response = await fetch(`${import.meta.env.PUBLIC_STRAPI_URL}/api/${endpoint}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching from Strapi:', error);
return null;
}
}

Now, let’s use this in one of our Astro pages. Here’s how you can fetch and display blog posts:

---
import { fetchApi } from '../lib/strapi';
const response = await fetchApi('posts');
const posts = response.data;
---
<div class="posts-grid">
{posts.map((post) => (
<article class="post-card">
<h2>{post.attributes.title}</h2>
<p>{post.attributes.description}</p>
</article>
))}
</div>

Geometric stone formations with natural textures and layers showcasing strength and structure. Color palette: Perfect red ochre and off-white with subtle gradients. Camera angle: Close-up macro shot highlighting texture details ultra-realistic cinematic 8K UHD high resolution sharp and detail

Handling Images and Media

When working with images from Strapi, you’ll need to construct the full URL. Here’s a helper function:

export function getStrapiMedia(url) {
if (!url) return null;
return `${import.meta.env.PUBLIC_STRAPI_URL}${url}`;
}

Best Practices and Tips

  1. Always implement error handling for your API calls
  2. Use TypeScript interfaces for better type safety
  3. Consider implementing caching for better performance
  4. Use loading states to improve user experience

Remember that Astro’s partial hydration feature can help you optimize your site’s performance by only sending JavaScript where it’s needed!

Deep space nebula with swirling cosmic clouds and starlight expressing infinite possibilities. Color palette: Dusty blue concrete and bright white stars against black space. Camera angle: Deep space perspective capturing vast cosmic scale high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

And there you have it! You’ve successfully connected your AstroJS application to a Strapi backend. This powerful combination gives you the flexibility of a headless CMS with the performance benefits of Astro’s static site generation. Happy coding!

icons/code-outline.svg AstroJs Blogs
Astro is an all-in-one web framework. It includes everything you need to create a website, built-in.
icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.