Node.js
Node.js is a JavaScript runtime built on Chrome's V8 engine that allows you to run JavaScript server-side.
Cosmic makes a great Node.js CMS for your Node.js websites and apps.
Before adding any code, make sure to follow the Initial Setup at the start of this section to set up your content in Cosmic. Then take the following steps to add Cosmic-powered content to your Node.js apps:
1. Install Express
You can use the popular Express website framework to get a Node.js Cosmic website up and running quickly. Start by creating a project folder and installing Express and Cosmic.
mkdir cosmic-node-appcd cosmic-node-appnpm i express cosmicjs
4. Create an index.js
file
Find your Bucket slug and API read key in Bucket Settings > API Access after logging in.
// index.jsconst express = require("express");const app = express();const Cosmic = require("cosmicjs");const api = Cosmic();const PORT = process.env.PORT || 3000;// Set these values, found in Bucket > Settings after logging in at https://app.cosmicjs.com/loginconst bucket = api.bucket({slug: "YOUR_BUCKET_SLUG",read_key: "YOUR_BUCKET_READ_KEY",});app.get("*", async (req, res) => {const data = await bucket.getObjects({query: {type: "posts",},props: "slug,title,content,metadata", // Limit the API response data by props});const posts = data.objects;let markup = ``;posts.map((post) => {markup += `<div style="margin-bottom: 20px"><div><img alt="" src="${post.metadata.hero.imgix_url}?w=400"/></div><div>${post.title}</div></div>`;});res.set("Content-Type", "text/html");res.send(markup);});app.listen(PORT, () => {console.log("Your Cosmic app is running at http://localhost:" + PORT);});
4. Start your app
Start your app, and go to http://localhost:3000. Dance 🎉
node index.js