Steven

Mercatante

Steven Mercatante

Use Custom Post URLs in Gatsby

By default, Gatsby generates URLs for posts from your directory structure. For example, if you have a directory named gatsby-custom-urls, your post's URL will be https://mysite.com/gatsby-custom-urls. But what if you want to use a different URL (say, use-custom-urls-in-gatsby) while keeping the directory structure the same? That's the problem I ran into. I have a specific naming and organization scheme for my directories that should be independent of the post's URL.

Lucky for us, we can change how these URLs are generated.

The Solution

First, make sure all of your posts have a slug attribute in its frontmatter. Here's the frontmatter for this post:

---
title: Use Custom Post URLs in Gatsby
date: '2019-10-08'
slug: 'use-custom-urls-in-gatsby'
tags: ['gatsby']
published: true
---

Make sure you restart the Gatsby dev server after adding new fields to frontmatter for the first time, otherwise you won't be able to query them.

The logic to create the URLs is in gatsby-node.js. Look for the call to createPage. Mine looks like this:

// gatsby-node.js
createPage({
path: post.node.frontmatter.slug,
component: articleTemplate,
context: {
slug: post.node.frontmatter.slug,
},
})

The line we care about is path: post.node.frontmatter.slug - it basically tells Gatsby "hey, construct the URL for this post based off of the slug attribute."

Caveats

One of the nice things about having Gatsby autogenerate URLs from the directory structure is that you'll never have two identical URLs for posts, since you can't have identically named directories. Using my method above, you need to make sure you don't use the same slug for different posts (but that's easy to do.)

You also need to make sure that every post has a slug attribute.