Skip to content

Next.js

Next.js is a framework for building React websites and apps.

Cosmic makes a great Next.js CMS for your Next.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 Next.js apps:

1. Install a new Next.js app

You can use Create Next App to install a new Next.js app that includes tooling and configurations. When prompted, select default starter app.

npm i -g create-next-app
create-next-app cosmic-next-app

2. Install the Cosmic NPM module

cd cosmic-next-app
npm i cosmicjs

3. Add the following code into your pages/index.js file

Find your Bucket slug and API read key in Bucket Settings > API Access after logging in.

// pages/index.js
import Head from "next/head";
const Cosmic = require("cosmicjs");
const api = Cosmic();
// Set these values, found in Bucket > Settings after logging in at https://app.cosmicjs.com/login
const bucket = api.bucket({
slug: "YOUR_BUCKET_SLUG",
read_key: "YOUR_BUCKET_READ_KEY",
});
function Blog({ posts }) {
return (
<div className="container">
<Head>
<title>Cosmic App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
{posts.map((post) => (
<div key={post.slug}>
<h3>{post.title}</h3>
<img alt="" src={`${post.metadata.hero.imgix_url}?w=400`} />
</div>
))}
</div>
);
}
export async function getStaticProps() {
const data = await bucket.getObjects({
query: {
type: "posts",
},
props: "slug,title,content,metadata", // Limit the API response data by props
});
const posts = await data.objects;
return {
props: {
posts,
},
};
}
export default Blog;

4. Start your app

Start your app, and go to http://localhost:3000. Dance 🎉

npm run dev

Next steps

  1. Learn more about Objects.
  2. Learn more about Queries.
  3. Learn more about Metafields.

Videos

  1. Getting Started with Cosmic CMS and Next.js.
  2. Building a Blog with Cosmic CMS and Next.js.

More resources

  1. Install pre-built Next.js templates.
  2. Read Next.js + Cosmic articles.