Adding a Path Prefix
Many applications are hosted at something other than the root (
/) of their domain.
For example, a Gatsby blog could live at
example.com/blog/, or a site could be hosted on GitHub Pages at
Each of these sites need a prefix added to all paths on the site. So a link to
/my-sweet-blog-post/ should be rewritten as
Adding the path prefix is a two step process, as follows:
Firstly, add a
pathPrefix value to your
The final step is to build your application with the
--prefix-paths flag, like so:
If this flag is not passed, Gatsby will ignore your
pathPrefix and build the site as if hosted from the root domain.
Gatsby provides APIs and libraries to make using this feature seamless. Specifically, the
Link component has built-in functionality to handle path prefixing.
For example, if you want to link to the location
/page-2, but the actual link will be prefixed (e.g.
/blog/page-2); you don’t need to hard code the prefix into your links. By using the Gatsby
Link component, paths will automatically be prefixed with the
pathPrefix value assigned in your
gatsby-config.js file. If you later migrate away from using a path prefix, your links will still work seamlessly.
For example, when navigating to the
page-2 location in the
Link component below; the location will be automatically prefixed with your assigned
If you want to do programmatic/dynamic navigation, this is also possible! Expose the Gatsby
navigate helper, and this too automatically handles path prefixing.
For pathnames you construct manually, there’s a helper function,
withPrefix that prepends your path prefix in production (but doesn’t during development where paths don’t need to be prefixed).
This feature works seamlessly with
assetPrefix. Build out your application with the
--prefix-paths flag and you’ll be well on your way to hosting an application with its assets hosted on a CDN, and its core functionality available behind a path prefix.
Edit this page on GitHub