Logo

dev-resources.site

for different kinds of informations.

Notion for NextJS CMS

Published at
6/21/2024
Categories
notion
nextjs
cms
blog
Author
pranjal_sharma_38482a3041
Categories
4 categories in total
notion
open
nextjs
open
cms
open
blog
open
Author
25 person written this
pranjal_sharma_38482a3041
open
Notion for NextJS CMS

Notion has become a popular productivity tool for individuals and teams. Did you know that Notion can also serve as a backend for your web applications? In this article, weā€™ll explore the benefits of using Notion as a backend for a Next.js application and demonstrate how to do it using the Notion API and TypeScript.

Prerequisites

Before we get started, make sure you have the following:

  • A Notion account
  • A Notion API key
  • A Next.Js project set up with TypeScript
  • The notion-client package installed

To get your Notion API key, go to your Notion integrations page, create a new integration, and copy the API key. To install the notion-client package, run the following command:

npm install notion-client
Enter fullscreen mode Exit fullscreen mode

1) Create a Notion database

First, letā€™s create a Notion database to store our blog posts. To do this, go to your Notion dashboard and create a new page. In the page properties, click the ā€œAdd a databaseā€ button, and select ā€œBlog Postsā€ as the database template.

This will create a database with the following properties:

  • Date
  • Tags
  • Title
  • Content Feel free to customize the properties to suit your needs.

Step 2: Fetch data from Notion

Next, letā€™s fetch the data from Notion using the Notion API. Create a new file called notion.ts in your Next.js project, and add the following code:

import { Client } from '@notionhq/client';


const notion = new Client({ auth: process.env.NOTION_API_KEY });
export async function getBlogPosts() {
  const databaseId = process.env.NOTION_DATABASE_ID;
  const response = await notion.databases.query({
    database_id: databaseId,
  });
  return response.results.map((page) => ({
    id: page.id,
    title: page.properties['Title'].title[0].text.content,
    date: page.properties['Date'].date.start,
    tags: page.properties['Tags'].multi_select.map((tag) => tag.name),
    content: page.properties['Content'].rich_text[0].text.content,
  }));
}

Enter fullscreen mode Exit fullscreen mode

In this code, weā€™re creating a new Client object from the notion-client package, using the NOTION_API_KEY environment variable to authenticate. Weā€™re also defining a function called getBlogPosts that retrieves the blog posts from Notion. Weā€™re using the database_id environment variable to specify the ID of the Notion database we created earlier. Then, weā€™re using the databases.query method to retrieve the data from the database. The databases.query method returns an array of pages, where each page represents a blog post. Weā€™re mapping over the results and extracting the relevant properties (title, date, tags, and content) from each page.

Step 3: Create a Next.js API route

Next, letā€™s create a Next.js API route to serve our blog posts. Create a new file called blog.ts in the pages/api directory, and add the following code:

import { NextApiRequest, NextApiResponse } from 'next';
import { getBlogPosts } from '../../lib/notion';

...

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const posts = await getBlogPosts();
  res.status(200).json(posts);
}
Enter fullscreen mode Exit fullscreen mode

This code defines a new API route that retrieves the blog posts using the getBlogPosts function we defined earlier. Weā€™re using the NextApiRequest and NextApiResponse types from Next.js to ensure type safety.

Step 4: Display the blog posts on the frontend

Finally, letā€™s display the blog posts on the frontend. Create a new file called index.tsx in the pages directory, and add the following code:

import { GetStaticProps } from 'next';
import { getBlogPosts } from '../lib/notion';

export const getStaticProps: GetStaticProps = async () => {
  const posts = await getBlogPosts();
  return {
    props: {
      posts,
    },
  };
};
interface Post {
  id: string;
  title: string;
  date: string;
  tags: string[];
  content: string;
}
interface Props {
  posts: Post[];
}
export default function Home({ posts }: Props) {
  return (
    <div>
      {posts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.date}</p>
          <ul>
            {post.tags.map((tag) => (
              <li key={tag}>{tag}</li>
            ))}
          </ul>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this code, weā€™re using the GetStaticProps function from Next.js to fetch the blog posts at build time. Weā€™re defining a new interface called Post to represent a single blog post, and another interface called Props to represent the props of our Home component. In the Home component, weā€™re using the map method to render each blog post as a div element. Weā€™re displaying the title, date, tags, and content of each post.

Step 5: Run the application

Thatā€™s it! You can now run your application using the following command:

npm run dev
Enter fullscreen mode Exit fullscreen mode
notion Article's
30 articles in total
Favicon
Why Most Students Struggle with Organization (And How Notion Templates Can Help)
Favicon
Why Your Notion Templates Arenā€™t Selling (And How to Fix It)
Favicon
Extract metadata of paper and export it to Notion DB
Favicon
Organize Your Gifts Effortlessly with This Notion Template šŸŽ
Favicon
Why Most Notion Templates Fail Businesses (And How to Create Ones That Work)
Favicon
Un blog statique sur mesure avec Notion headless
Favicon
Learning GO : 09 - Packages
Favicon
Notion is making a super customizable email app
Favicon
Project Planning
Favicon
Learning GO : 08 - File Handling, Error Handling
Favicon
Learning GO: 07 - Loops
Favicon
Learning GO: 06 - Function return values, if condition
Favicon
Learning GO: 05 - Function Declaration
Favicon
I Analyzed 4 Successful Products to Find These Powerful UI Design and Implementation Principles
Favicon
How I Sync my Obsidian Notes For Free !
Favicon
Best Notion Time Tracking Software
Favicon
Using Notion as a CMS and create a personal blog with React
Favicon
How to Embed Live Reports in Notion Using Flowtrail AI
Favicon
3+ Productivity Hacks with Notion
Favicon
Building a personal blog with Next.js and Notion
Favicon
Notion for NextJS CMS
Favicon
Count everything in your Notion workspace
Favicon
The Best Notion Alternatives in 2024
Favicon
Install Notion on Ubuntu
Favicon
Free Notion Style Avatar Generator
Favicon
Discover Your Notion Page Insights with Notion Statistics
Favicon
Bot Telegram + Notion
Favicon
Building a Notion-style activity feed with Next.js and shadcn/ui
Favicon
I switched from Notion to Obsidian
Favicon
Launch your startup in 450+ communities

Featured ones: