Strapi is an open-source, Node.js-based Headless CMS that can easily build customizable APIs and manage web content with any front-end framework. One of the most prominent features it has is the Media Library plugin; with this, you can upload various media files (images, videos, documents) and organize them as well. This is great for making media-heavy apps such as galleries.
In this tutorial, you'll learn how to build an Astrojs Image Gallery using Astro and Strapi's Media Library plugin.
Here is a demo of the project we'll be building throughout this tutorial:
Here’s a quick summary of what we will learn in this tutorial:
One of the best things about Strapi is its powerful Media Library, which provides a smooth way to manage your media files and organize content with ease. Here are some of the main features:
By integrating Strapi Media Library, we get the best of both worlds, Powered by Astro. Some of the advantages include:
Before we begin, ensure you have the following:
The complete code for this tutorial can be found in this GitHub repository. Clone the repo and follow along!
To create a new Strapi 5 project, run the following command:
npx create-strapi@latest gallery-project
The above command will prompt you to select the preferred configurations for your Strapi 5 project. Your selection should look like the screenshot below:
After selecting the above configurations, it will scaffold a new Strapi CMS project and install the necessary Node.js dependencies. Once setup is complete, create your admin account by filling out the required forms.
Next, stop the server using Ctrl + C
and Configure the upload plugin in the config/plugins.js
file. By default, Strapi 5 provides a provider that uploads files to a local directory, which by default will be public/uploads/
in your Strapi project. Strapi 5 supports various storage options for uploads, such as Firebase, Cloudflare, Amazon S3, and Cloudinary. For simplicity, we will use the Local storage provider in this example:
1export default ({ env }) => ({
2 upload: {
3 config: {
4 providerOptions: {
5 localServer: {
6 maxage: 300000
7 },
8 },
9 },
10 },
11});
To allow public access to upload media files, navigate to the Settings panel from the Strapi dashboard. Under USERS & PERMISSIONS PLUGIN, select Roles. Then click on Public from the roles table.
Scroll down to Upload, tick Select find, findOne, upload, and click Save.
Once the API access is configured, you can upload media files to the Media Library. Here’s how:
In the admin panel, click on the Media Library section from the left sidebar. Click Add new assets -> FROM COMPUTER -> Browse Files to select files from your computer.
Upload at least three image files for this demo.
Now that Strapi is up and running with your media content, we’ll move on to setting up the front-end using Astro. Astro is a modern web framework that makes building fast websites a breeze by supporting component-based frameworks like React, Svelte, Vue, and others.
To start, let’s create a new Astro project. Run the following commands in your terminal:
npm create astro@latest media-app
The above command will also prompt you to select the configuration for your project. For the demonstration in this tutorial, your selection should look like the screenshot below:
Then navigate into the new project directory and start the Astro development server:
cd ./my-media-app
npm run dev
This will spin up a development environment and open your site in the browser. You'll see a default Astro welcome page, but don't worry; we'll replace this with our image gallery soon!
Now, let’s integrate Strapi and Astro by fetching image data from Strapi’s API. Strapi exposes a flexible REST API out of the box, but you can also use GraphQL if you’ve installed the GraphQL plugin in Strapi. For this guide, we’ll use the REST API.
Now, in your Astro project, create a new API utility in the utils/api.ts
file to fetch gallery data from Strapi:
1import { API_URL } from "../constants";
2
3export async function fetchGallery() {
4 const response = await fetch(`${API_URL}/api/upload/files`);
5 if (!response.ok) {
6 throw new Error("Failed to fetch gallery data");
7 }
8 const data = await response.json();
9 console.log(data);
10 return data;
11}
This function makes a simple HTTP GET
request to Strapi’s /gallery
endpoint. You can adjust the API_URL
if you’re hosting Strapi on a different URL. The function returns a JSON object that contains your gallery images.
Create a constant.ts
file in the src
folder to define the app content variables. Here, we'll define the API_URL
so we can reuse it across the application.
1export const API_URL = "http://localhost:1337";
Now that we can fetch data from Strapi, let’s display it in a responsive front-end layout. We'll use a basic CSS Grid to create a gallery layout that adapts to different screen sizes.
First, update your pages/index.astro
file to create a page where the gallery will live:
1---
2import { fetchGallery } from "../utils/api";
3import { API_URL } from "../constants";
4
5const gallery = await fetchGallery();
6
7interface Gallary {
8 url: string;
9 id: number;
10 name: string;
11}
12---
13
14<html>
15 <head>
16 <title>Astro Image Gallery</title>
17 <style>
18 .gallery {
19 display: grid;
20 grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
21 gap: 20px;
22 }
23 .gallery-item {
24 border: 1px solid #ccc;
25 padding: 10px;
26 text-align: center;
27 }
28 .gallery-item img{
29 width: 100%;
30 }
31 </style>
32 </head>
33 <body>
34 <h1>Image Gallery</h1>
35 <div class="gallery">
36 {
37 gallery.map((item: Gallary) => (
38 <div class="gallery-item" key={item.id as any}>
39 <img src={API_URL + item.url} alt={item.name} />
40 <p>{item.name}</p>
41 </div>
42 ))
43 }
44 </div>
45 </body>
46</html>
In the above code snippet, we use fetchGallery()
in the front matter section of the Astro page to retrieve image data. The CSS grid is used to create a responsive gallery layout where each image is displayed in a grid item. The map()
function loops through the fetched gallery data, rendering each image with its name below it.
Now, create a dynamic page to preview each image dynamically. Create an image/[id].astro
file in your pages
directory. Add the code snippet below:
1---
2import { API_URL } from "../../constants";
3
4const { id } = Astro.params;
5
6let imageData = null;
7let error = null;
8
9try {
10 const response = await fetch(`${API_URL}/api/upload/files/${id}`);
11
12 if (!response.ok) {
13 throw new Error(`Failed to fetch image data for ID ${id}`);
14 }
15
16 imageData = await response.json();
17} catch (err: any) {
18 error = err.message;
19}
20---
21
22<html lang="en">
23 <head>
24 <title>
25 {imageData ? imageData.name : "Image Not Found"} - Image Gallery
26 </title>
27
28 <style>
29 .container {
30 max-width: 800px;
31 margin: 0 auto;
32 padding: 20px;
33 }
34 .image-container {
35 text-align: center;
36 }
37 .image-container img {
38 max-width: 100%;
39 height: auto;
40 }
41 .image-info {
42 margin-top: 20px;
43 }
44 .back-link {
45 display: inline-block;
46 margin-top: 20px;
47 padding: 10px 15px;
48 background-color: #007bff;
49 color: white;
50 text-decoration: none;
51 border-radius: 5px;
52 }
53 .error {
54 color: red;
55 font-weight: bold;
56 }
57 </style>
58 </head>
59 <body>
60 <div class="container">
61 {
62 error ? (
63 <div class="error">
64 <h1>Error</h1>
65 <p>{error}</p>
66 <a href="/" class="back-link">
67 Back to Gallery
68 </a>
69 </div>
70 ) : (
71 <>
72 <h1>{imageData.name}</h1>
73 <div class="image-container">
74 <img src={`${API_URL}${imageData.url}`} alt={imageData.name} />
75 </div>
76 <div class="image-info">
77 <p>
78 <strong>File name:</strong> {imageData.name}
79 </p>
80 <p>
81 <strong>Upload date:</strong>{" "}
82 {new Date(imageData.createdAt).toLocaleString()}
83 </p>
84 <p>
85 <strong>File size:</strong> {(imageData.size / 1024).toFixed(2)}{" "}
86 KB
87 </p>
88 </div>
89 </>
90 )
91 }
92 <a href="/" class="back-link">Back to Gallery</a>
93 </div>
94 </body>
95</html>
The code above sets up a dynamic page in an Astro project that displays a single image from Strapi’s media library based on the image's unique ID. The getStaticPaths
function automatically generates routes for each image, allowing you to click on an image and view its details on a separate page. Along with displaying the image, the page shows useful metadata like the image name, upload date, and file size. If there’s an issue fetching the image (for example, if the image doesn’t exist), an error message is displayed. A "Back to Gallery" button is also included to make navigation easy.
Then, since our code uses server-side rendering, update Astro configuration in the astro.config.mjs
file to allow it:
1import { defineConfig } from 'astro/config';
2
3// https://astro.build/config
4export default defineConfig({
5 output: 'server',
6});
Update the code in your pages/index.astro
file to be able to navigate to this new page:
1 ...
2 <div class="gallery">
3 {
4 gallery.map((item: Gallary) => (
5 <div class="gallery-item" key={item.id}>
6 <a href={`/image/${item.id}`}>
7 <img src={API_URL + item.url} alt={item.name} />
8 <p>{item.name}</p>
9 </a>
10 </div>
11 ))
12 }
13 </div>
14 ...
Now click on any of the images to navigate to view more details about the image:
Finally, let’s handle image uploads directly from the Astro front-end and send them to Strapi.
We’ll create a form in Astro that allows users to upload images. The form sends a POST
request to Strapi’s /api/upload
endpoint. Update the code in your pages/index.astro
to:
1---
2import { fetchGallery } from "../utils/api";
3import { API_URL } from "../constants";
4
5const gallery = await fetchGallery();
6
7interface Gallery {
8 url: string;
9 id: number;
10 name: string;
11}
12---
13
14<html lang="en">
15 <head>
16 <title>Astro Image Gallery</title>
17 <style>
18 .gallery {
19 display: grid;
20 grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
21 gap: 20px;
22 }
23 .gallery-item {
24 border: 1px solid #ccc;
25 padding: 10px;
26 text-align: center;
27 }
28 .gallery-item img {
29 width: 100%;
30 transition: transform 0.3s ease;
31 }
32 .gallery-item img:hover {
33 transform: scale(1.05);
34 }
35 .gallery-header {
36 display: flex;
37 justify-content: space-between;
38 }
39 .modal {
40 display: none;
41 position: fixed;
42 top: 0;
43 left: 0;
44 width: 100%;
45 height: 100%;
46 background-color: rgba(0, 0, 0, 0.5);
47 justify-content: center;
48 align-items: center;
49 }
50 .modal-content {
51 background-color: white;
52 padding: 20px;
53 border-radius: 8px;
54 width: 300px;
55 text-align: center;
56 }
57 .modal.show {
58 display: flex;
59 }
60 .close {
61 position: absolute;
62 top: 10px;
63 right: 10px;
64 cursor: pointer;
65 font-size: 24px;
66 }
67 </style>
68 </head>
69 <body>
70 <div class="gallery-header">
71 <h1>Image Gallery</h1>
72 <button id="addImageBtn">Add New Image</button>
73 </div>
74
75 <div class="gallery">
76 {
77 gallery.map((item: Gallery) => (
78 <div class="gallery-item" key={item.id}>
79 <a href={`/image/${item.id}`}>
80 <img src={API_URL + item.url} alt={item.name} />
81 <p>{item.name}</p>
82 </a>
83 </div>
84 ))
85 }
86 </div>
87
88 <div class="modal" id="uploadModal">
89 <div class="modal-content">
90 <span class="close" id="closeModal">×</span>
91 <h2>Upload New Image</h2>
92 <form id="uploadForm">
93 <input type="file" accept="image/*" id="fileInput" />
94 <br /><br />
95 <button type="submit">Upload Image</button>
96 </form>
97 </div>
98 </div>
99
100 <script define:vars={{ API_URL }}>
101 let showModal = false;
102 let selectedFile = null;
103
104 function toggleModal() {
105 showModal = !showModal;
106 document
107 .getElementById("uploadModal")
108 .classList.toggle("show", showModal);
109 }
110
111 function handleFileChange(event) {
112 selectedFile = event.target.files[0];
113 }
114
115 async function handleSubmit(event) {
116 event.preventDefault();
117
118 if (!selectedFile) {
119 alert("Please select an image to upload");
120 return;
121 }
122
123 const formData = new FormData();
124 formData.append("files", selectedFile);
125
126 try {
127 const response = await fetch(`${API_URL}/api/upload`, {
128 method: "POST",
129 body: formData,
130 });
131 console.log(response);
132 if (response.ok) {
133 alert("Image uploaded successfully!");
134 toggleModal();
135 location.reload();
136 } else {
137 alert("Failed to upload image.");
138 }
139 } catch (error) {
140 console.error("Error uploading image:", error);
141 alert("An error occurred while uploading the image.");
142 }
143 }
144
145document
146 .getElementById("addImageBtn")
147 .addEventListener("click", toggleModal);
148 document
149 .getElementById("closeModal")
150 .addEventListener("click", toggleModal);
151 document
152 .getElementById("fileInput")
153 .addEventListener("change", handleFileChange);
154 document
155 .getElementById("uploadForm")
156 .addEventListener("submit", handleSubmit);
157 </script>
158 </body>
159</html>
To allow users to add new images from the app, we added a modal with a file field and upload button, then added event listeners to show, close the modal, and upload the selected image to the Strapi media library.
You can now add new images to your gallery by clicking the Add New Image button.
In this tutorial, we have learned how to build an image gallery app with Astro.js and Strapi. With Astro and Strapi, we built an Astrojs image gallery.
With this, we have demonstrated how Strapi and Astro can be seamlessly integrated for media-rich applications.
I'm a Software Engineer and Technical Writer who specializes in Node.js and JavaScript. I'm passionate about technology and sharing knowledge.