Sometimes, Gatsby developers need to implement sites that fit into an existing path system on a domain that houses other sites. For instance, you may have a Gatsby site that coexists with other Gatsby sites and needs to be under a particular path (say, example.com/gatsby-site). As a matter of fact, some hosting providers—notably GitHub Pages—obligate the use of an internal path rather than the domain root (e.g., example.github.io/gatsby-site), unless a custom domain is used.
Without a path prefix, the site itself and any assets that are located within the site’s internal directory structure will fail upon deployment. All paths on the site, and all paths to site assets, require a path prefix in this scenario.
To configure a path prefix, add a pathPrefix
key to your gatsby-config.js file, as follows:
// gatsby-config.js
module
.
exports
=
{
pathPrefix
:
`/gatsby-site`
,
}
For instance, if you have a Gatsby blog that needs to be located under the path prefix /blog after the domain, you can enforce that distinction in your Gatsby configuration file:
// gatsby-config.js
module
.
exports
=
{
pathPrefix
:
`/blog`
,
}
Whenever you perform a Gatsby build or serve your Gatsby site through a server, you must also pass the --prefix-paths
flag in order to ensure that your path prefix value is accounted for during the build process. Note that this is also the case when using hosting providers that ask developers to provide a build command in deployment configuration.
To build your Gatsby site with the path prefix, execute the following:
$
gatsby
build
--prefix-paths
To serve the site, execute the following:
$
gatsby
serve
--prefix-paths
Without this flag, even if you configure the path prefix within your Gatsby configuration file, the build process will ignore your pathPrefix
value and build the site assuming that you wish to situate it in the domain root.
NOTE
The Gatsby <Link />
component respects path prefixes and will ensure that path prefixes are accounted for during the build process. This means that you never need to include the path prefix when you add a path to the to
prop of the component. Gatsby’s navigate
helper also respects path prefixes. For more information, consult the Gatsby documentation’s guide to in-app linking with path prefixes. Where you do need to construct paths manually because neither of these solutions works for your use case, you can use the withPrefix
helper provided by Gatsby to manually add the path prefix.
Leave a Reply