Follow the steps below to get started with Cosmic to power content for your Fastify application.
Create folder and install Fastify
mkdir cosmic-fastify
cd cosmic-fastify
npm init
npm i express
Install the Cosmic JavaScript SDK
Install the Cosmic JavaScript SDK in the location of the codebase.
npm i @cosmicjs/sdk
Add an Object type in the Cosmic dashboard
Log in to the Cosmic dashboard and create a new Blog Posts
Object type in a new or existing Project with the following metafields:
- Image: Image type with key
image
- Content: Rich text with key
content
Add content
Add a few blog posts to get some content ready to be delivered.
Create a new file app.js
and add the following:
// app.js
import Fastify from 'fastify';
const fastify = Fastify({
logger: true,
});
import { createBucketClient } from '@cosmicjs/sdk';
const cosmic = createBucketClient({
bucketSlug: process.env.BUCKET_SLUG || '',
readKey: process.env.BUCKET_READ_KEY || '',
});
fastify.get('/', async (request, reply) => {
reply.header('Content-Type', 'text/html; charset=utf-8');
const { objects: posts } = await cosmic.objects
.find({
type: 'blog-posts',
})
.props('title,metadata.image,metadata.content');
let html = '';
posts?.map((post) => {
html += `<div>
<div>${post.title}</div>
<div>
<img
src="${post.metadata.image.imgix_url}?w=500&auto=format,compression"
alt="${post.title}"
/>
</div>
<div>${post.metadata.content}</div>
</div>`;
});
return html;
});
const start = async () => {
try {
await fastify.listen({ port: 3000 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
Add your Cosmic API keys
In a new file titled .env.local
add the following environment variables and make sure to switch out the values with your Cosmic API keys found in Project / API keys.
# .env.local
BUCKET_SLUG=add_your_bucket_slug_here
BUCKET_READ_KEY=add_your_bucket_read_key_here
Start the app
Start your app with the following command, go to http://localhost:3000, and see your blog posts. Note: we are using bun which enables environment variable reading without a separate package and the ability to use ES6 imports.
bun app.js