Skip to content

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.

Terminal window
npm create astro@latest
  1. 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 [];
    }
    }
  2. Edit astro.config.mjs file, add node 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
    }
    }
    }
    }
    //...
    });
  3. Create and configure .env file. (See Environment Variables)

    • .env
    • astro.config.mjs
    • package.json
  1. Setup server and install CMS

    Terminal window
    npm install @opengis/cms@latest
  2. Start CMS application.

    Terminal window
    node --env-file=.env server

    If done correctly, you should see the following (or similar) message in the console:

    Terminal window
    Server is running on http://localhost:3000
  3. You can start creating content collections in CMS web-interface (see Creating content).

Astro components can fetch data from the CMS using the getContents function.

/src/pages/blog/index.astro
---
import { getContents } from "@/utils/cms";
let { rows } = await getContents("blog"); // collection name
---
<Layout title="Blog">
<BlogList data={rows} />
</Layout>
/src/pages/blog/[slug].astro
---
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>