diff --git a/packages/gatsby-link/README.md b/packages/gatsby-link/README.md
index 1288cbacd87cc..495c82284d230 100644
--- a/packages/gatsby-link/README.md
+++ b/packages/gatsby-link/README.md
@@ -52,3 +52,24 @@ render () {
}
```
+
+## Prefixed paths helper
+
+Gatsby allows you to [automatically prefix links](/docs/path-prefix/) for sites hosted on Github Pages or other places where your site isn't at the root of the domain.
+
+This can create problems during development as pathnames won't be prefixed. To handle both, gatsby-link exports a helper function `withPrefix` that prepends the prefix during production but doesn't in development.
+
+```jsx
+import { withPrefix } from "gatsby-link"
+
+const IndexLayout = ({ children, location }) => {
+ const isHomepage = location.pathname === withPrefix('/');
+
+ return (
+
+
Welcome {isHomepage ? 'home' : 'aboard'}!
+ {children()}
+
+ )
+}
+```
diff --git a/packages/gatsby-link/src/index.js b/packages/gatsby-link/src/index.js
index d2cbb7692f5ec..cfabd3ae10a16 100644
--- a/packages/gatsby-link/src/index.js
+++ b/packages/gatsby-link/src/index.js
@@ -8,6 +8,10 @@ if (typeof __PREFIX_PATHS__ !== `undefined` && __PREFIX_PATHS__) {
pathPrefix = __PATH_PREFIX__
}
+export function withPrefix(path) {
+ return pathPrefix + path
+}
+
function normalizePath(path) {
return path.replace(/^\/\//g, `/`)
}
@@ -49,7 +53,7 @@ class GatsbyLink extends React.Component {
}
this.state = {
- to: normalizePath(pathPrefix + props.to),
+ to: normalizePath(withPrefix(props.to)),
IOSupported,
}
this.handleRef = this.handleRef.bind(this)
@@ -58,7 +62,7 @@ class GatsbyLink extends React.Component {
componentWillReceiveProps(nextProps) {
if (this.props.to !== nextProps.to) {
this.setState({
- to: normalizePath(pathPrefix + nextProps.to),
+ to: normalizePath(withPrefix(nextProps.to)),
})
// Preserve non IO functionality if no support
if (!this.state.IOSupported) {
@@ -159,5 +163,5 @@ GatsbyLink.contextTypes = {
export default GatsbyLink
export const navigateTo = pathname => {
- window.___navigateTo(normalizePath(pathPrefix + pathname))
+ window.___navigateTo(normalizePath(withPrefix(pathname)))
}