Astro Integration
Astro is a static site builder that allows you to create static sites with a modern, fast, and secure approach.
To integrate our CMS with Astro, you need to create a new Astro project and add the CMS to it.
Create a new Astro project
Section titled “Create a new Astro project”npm create astro@latest
Install dependencies
Section titled “Install dependencies”-
Add the following file to the
src/utils
directory of your Astro project.Directorysrc
Directoryutils
- cms.js
- astro.config.mjs
- package.json
/src/utils/cms.js import { loadEnv } from "vite";const data = loadEnv(process.env.NODE_ENV, process.cwd(), "");const host = data.CMS_HOST;const TOKEN = data.CMS_TOKEN;export async function getContents(type, params = {}) {const { limit = 10, page, tags, desc } = params;const options = {method: 'GET',headers: {'Content-Type': 'application/json',Authorization: `Bearer ${TOKEN}`,}};try {const ifFilter = tags ? `&filter=tags=${tags}` : '';const ifOrder = desc ? `&order=created_at` : '&order=created_at&desc=1';const ifPage = page ? `&page=${page}` : '';const fetchUrl = `${host}/api/cms/${type}?limit=${limit}${ifFilter}${ifPage}${ifOrder}`;const body = await fetch(fetchUrl, options);if (body.status === 404) return [];const { rows, total, filtered } = await body?.json();return { rows, total, filtered };} catch (err) {console.log(err)return [];}} -
Edit
astro.config.mjs
file, addnode
adapter and proxy for fetching media files.import { defineConfig } from 'astro/config';import node from '@astrojs/node';export default defineConfig({//...output: "server",adapter: node({mode: 'middleware',}),vite: {server: {proxy: {'/files': {target: 'https://cms-host.com',changeOrigin: true,secure: false}}}}//...}); -
Create and configure
.env
file. (See Environment Variables)- .env
- astro.config.mjs
- package.json
Start CMS and create content collection
Section titled “Start CMS and create content collection”-
Setup server and install CMS
Terminal window npm install @opengis/cms@latest -
Start CMS application.
Terminal window node --env-file=.env serverIf done correctly, you should see the following (or similar) message in the console:
Terminal window Server is running on http://localhost:3000 -
You can start creating content collections in CMS web-interface (see Creating content).
Fetching data
Section titled “Fetching data”Astro components can fetch data from the CMS using the getContents
function.
Example of blog index page:
Section titled “Example of blog index page:”---import { getContents } from "@/utils/cms";let { rows } = await getContents("blog"); // collection name---
<Layout title="Blog"> <BlogList data={rows} /></Layout>
Example of blog slug page:
Section titled “Example of blog slug page:”---import { getContents } from "@/utils/cms";
const { slug } = Astro.params;const { rows } = await getContents("blog/" + slug);blog_post = rows[0] || null;---
<Layout title="Blog"> <BlogPage data={blog_post} /></Layout>