I have created a Gatsby app and configured gatsby-node.js
to a create client only paths, which are all working fine in development while directly accessing the
I looked in the public folder to find the index file for the client route I created
for netlify I added the below to the netlify.toml file at the root.
[[redirects]]
from = "/user/dashboard/"
to = "/user/index.html"
status = 200
For anyone who uses S3 (gatsby-plugin-s3) and CloudFront, I've resolve 302/404 by adding generateMatchPathRewrites: false
in the gatsby-plugin-s3 config and creating a Lambd@Edge function for origin request with code below:
exports.handler = async (event) => {
const request = event.Records[0].cf.request;
if (/^\/app\//i.test(request.uri)) {
request.uri = '/app/index.html';
}
return request;
};
Though 302/404 went away, I still have the issue when doing a hard refresh. For example when I am at /app/page2 and hit refresh, the default component in /app will load then half a second later the component in /app/page2 will show up but in a weird way. Some css classes of /app is mixed in /app/page2. If anyone has any idea about this, please let me know.
For Firebase hosting, I added the following to my firebase.json
:
"rewrites": [
{
"source": "**",
"destination": "/loading/index.html"
}
]
Then I created a new loading.js
file under /page
. With this configuration, Firebase first responds with loading.html
then Gatsby handles the client routing.
The Why
While the client-side router knows about this path, there is no corresponding HTML file. When the browser looks at the site it first loads the 404.html
file generated by gatsby, which includes the client-side router. Once the router completes its initialization it reads the path and loads the correct page. Meaning you end up at the right place but there's half a second of landing on the wrong page.
How to fix It
The general solution is to tell your server to redirect the /sample/
path to your /sample/index.html
file. The way to do this depends on your host, but I'll provide the name of the technique for various hosts in case you want to look it up. It's usually called URL Rewriting and should be supported by every major hosting platform.
Heroku
The Heroku section of the gatsby deploy documentation suggests using the heroku-buildpack-static module which has built-in support for "custom routes" which will solve this for your case using syntax like this:
{
"routes": {
"/sample/**": "sample/index.html",
}
}
AWS Amplify
You need to add the redirect in the AWS Amplify console. For this example, the params are:
/sample/<*>
/sample/index.html