HomeMore Tutorials

DIY Blog Part 2: NextJS

published about 1 year ago
in Tutorials

by Greg Murray

last updated about 1 year ago

nextjs
frontend
javascript
react
blogging
tutorial
software development

In my previous blog post I discussed Sanity, the headless CMS I am using to manage the posts on this blog. Now that that is out of the way, we can talk about how I have built the website itself to actually, you know, display those blog posts. After all, a headless CMS isn’t very useful without a head. In my case, the head will be powered by NextJS. Let’s get started.

Next is a React framework that provides a great developer experience (more on that later) and quick load times - especially when you have many static pages with data that can be retrieved ahead of time. Doesn’t that sound like I am just describing a blog?

I’ve begun to really enjoy using Next even without needing the fast load times. It has great features out of the box, particularly built-in, file-based routing. If there’s one thing that many developers dread about using React (other than state-management), it is routing. With Next, you can simply organize your website’s page structure using the structure of the files in your project. This does limit you to needing a structure that fits with that sort of organization, but realistically that is not a huge limitation.

On top of the straightforward file-based routing, Next also supports dynamic routing. For example, let’s say you have a folder called “posts” and in that folder you have an index.js and a [postId].js file.

1my-blog
2└── pages
3    └── posts
4        ├── index.js
5        └── [postId].js

In this example, the index.js file would match with the /posts route. Any route that follows the pattern /posts/123 would then match the [postId].js file. Each of those files can simply export a functional component which is what will be rendered when those routes are used. For dynamic routing, the component [postId].js exports will be given postId as a prop with the value provided in the route. So in the example given, the value of postId would be “123” which can be used however you wish.

The other feature that Next provides which is particularly useful for blogs is the ability to query for data before a page is built. Basically the way this works is you define a function called getStaticProps to get the data, and then getStaticPaths if you are doing this on a dynamic route page so that Next knows what routes it will end up creating. Next will create a page for each dynamic route that it retrieves (getStaticPaths) before the page is built and also get the data each page requires (getStaticProps). For a blog, that would mean retrieving the blog post based on the dynamic path (”123” in the previous example) and also retrieving all of the blog posts and creating dynamic paths for each. Here’s a more specific example using the file structure from before:

1const Post = ({ post }) => (
2  <div>
3    <h1>{post.title}</h1>
4    <p>{post.content}</p>
5  </div>
6);
7
8export default Post;
9
10export const getStaticProps = async ({ params }) => {
11  const post = await postService.getPost(params.postId); // using a fake postService
12
13  return {
14    props: {
15      post,
16    },
17  };
18};
19
20export const getStaticPaths = async () => {
21  const paths = await postService.getPosts(); // using a fake postService
22  return {
23    paths: paths.map((post) => ({
24      params: { postId: post.id },
25    })),
26  };
27};

Let’s break this down. The getStaticPaths function retrieves all of the appropriate blog posts first and then “populates” the paths with the retrieved ids so that going to those paths will actually correspond with a blog post. Then, for each of those paths which received a postId from the getStaticPaths, we use getStaticProps to get that specific blog post and hand that data off to the Post component’s props. This setup allows Next to build a page for every blog post ahead of time rather than at page load. When the app is built and deployed, all of the blog posts will be retrieved and have pages built for them. This is awesome because each page will be quick to load. The downside is that adding or updating a blog post would require the entire project to be rebuilt. For smaller sites this is not a huge problem but fortunately for larger sites Next already has a solution called Incremental Static Regeneration which you can learn more about in their docs.

Similar to my previous post about Sanity, this is not intended to be a full tutorial for NextJS. My main goal is to give you a taste of what it can do and how I used it to set up this blog. Hopefully you learned something or maybe you were even inspired to start a blog of your own. Either way thanks for reading and feel free to comment or reach out to me if you have any questions. I’ll see you in the next post.

Loading script...
home
Copyright© Greg Murray 2024