Building a Static Blog Using Next.js 13.4 App Router with Sanity.io

Posted by






Static blog with Next.js 13.4 app router with Sanity.io

Building a Static Blog with Next.js and Sanity.io

Static site generators have been gaining popularity in recent years due to their speed and security benefits. Next.js is a popular framework for building static websites and web applications, and when combined with Sanity.io, a headless CMS, it becomes a powerful tool for building dynamic and scalable blogs.

Getting Started

To get started with building a static blog using Next.js and Sanity, you will need to install the necessary packages and set up your project. First, install Next.js using the following command:

npm install next react react-dom

Next, create a new Next.js project using the Next.js CLI:

npx create-next-app@13.4 my-blog

Once your Next.js project is created, you can install the Sanity CLI and set up a new Sanity project:

npm install -g @sanity/cli
sanity init

Building the Blog

With your Next.js and Sanity projects set up, you can start building your blog. Begin by creating a new collection in your Sanity project to store your blog posts. Then, you can use the Next.js app router to create dynamic routes for each blog post. Here’s an example of how you can achieve this:


import { useRouter } from 'next/router'
import { getBlogPost } from '../lib/sanity'

export default function BlogPost({ post }) {
const router = useRouter()
if (router.isFallback) {
return

Loading...

}
return (

{post.title}

{post.content}

)
}

export async function getStaticPaths() {
const posts = await getAllBlogPosts()
return {
paths: posts.map((post) => ({
params: { slug: post.slug },
})),
fallback: false,
}
}

export async function getStaticProps({ params }) {
const post = await getBlogPost(params.slug)
return {
props: {
post,
},
}
}

Deploying the Blog

Once your blog is built, you can deploy it using a static site hosting service such as Vercel or Netlify. These services make it easy to deploy and manage your static blog, and provide features such as automatic builds and previews.

Conclusion

Building a static blog with Next.js and Sanity.io is a powerful and flexible way to create dynamic and scalable websites. With the combination of Next.js’ app router and Sanity’s headless CMS, you can create a fast and secure blog that can be easily deployed and managed. If you’re looking to build a blog that is both dynamic and static, consider using Next.js and Sanity.io for your next project.