I have deployed my site with Netlify, and I’m having trouble with the routing.
Here is my website: https://redux-co.netlify.com/
And my GitHub repo: https://github.com/jenna-m/redux-co
Specifically, if a user navigates to any page besides the home page and refreshes the page, the default Netlify 404 renders. From the 404 page, if I navigate back to the home page and refresh, the home page is rendered.
Also, my custom 404 page isn’t working as it does when I’m on localhost:3000, but I would like to get this refresh issue figured out first before dealing with my custom 404 component.
I’m using React and react-router, and I understand that since I’m using react-router, my website won’t deploy right out of the box.
This is my _redirects file, which is in the /public folder with my index.html file:
/* /index.html 200
This is my “build” located in package.json:
…
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && cp build/index.html build/404.html",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
…
I have read about other people experiencing this and what they’ve done to overcome the problem. This is what I’ve referenced so far…
https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/
https://hugogiraudel.com/2017/05/13/using-create-react-app-on-netlify/
This person was using Vue and not React, but I gave these solutions an attempt anyway:
https://github.com/vuejs/vuepress/issues/457#issuecomment-390206649
https://github.com/vuejs/vuepress/issues/457#issuecomment-463745656
This was simple and it worked for me. I found this link https://create-react-app.dev/docs/deployment#netlify
So as suggested by that link, I added a _redirects file inside the /public folder like /public/_redirects. I then pasted /* /index.html 200 into the _redirects file. I did all that in my VS Code, after which I pushed to github and then ofcourse my netlify re-deploys automatically everytime I push to github. My problem was solved and refresh nolonger brings the 404 error.
In my package.json, the build section looks like this;
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Note:
Some articles say that you need to add _redirects in the build folder, but then build folder is not among what gets pushed to github in my case, so that's why adding _redirects to public folder worked better for me, as the public folder can be pushed along with my code.
Add netlify.toml file to the root directory of your project and paste the following code in it:
[[redirects]]
from = "/*"
to = "/"
status = 200
push and redeploy your app and it's done.