93

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

1
  • hm, strange. Maybe you have set something wrong on Netlify settings
    – demkovych
    Commented Sep 23, 2019 at 15:52

18 Answers 18

176

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.

5
  • Hi this did help me while deploying my static site on NETLIFY, but when I tried same thing on RENDER platform, this hack didn't help. Any idea how to fix the same issue while deploying my static site on Render ? Commented Dec 14, 2022 at 18:16
  • @user14106566 Glad to know the hack helped when working with netlify. Unfortunately, I haven't worked with the Render platform and I am not able to tell why the hack wouldn't work.
    – manpikin
    Commented Dec 17, 2022 at 20:32
  • no worries at all, cause I have figured out a similar workaround with render deployment as well. While deploying your site, you just need to tweak the settings. Under settings there is a redirect tab, just edit it the same way like this _redirects file. Commented Dec 18, 2022 at 4:57
  • I used this same solution to fix my react-router site on Netlify, but now the Google Search Console is listing some of those pages with a "Soft 404" and declaring them non-indexable by Google. Has anyone seen this before? It could just be a temporary transition issue from my old site, but if not I want to fix it ASAP.
    – TimHayes
    Commented Mar 15, 2023 at 11:23
  • @TimHayes I haven't encountered that. Would be nice to let us know when you get a workaround.
    – manpikin
    Commented Mar 15, 2023 at 19:38
96

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.

2
  • 1
    +1 Accessing my react-app routes, such as /contact on netlify directly via URL (not via app UI) triggered 404. This file solved it.
    – Sandro
    Commented Sep 11, 2023 at 10:26
  • Thanks. This solution worked for me. I first tried _redirects in \public directory but it was not worked. Commented Dec 29, 2023 at 16:10
15

Remove _redirects from your public folder and move netlify.toml to the root of your git repo, more info. Also remove from build script && cp build/index.html build/404.html - you don't need that any more

7
  • 1
    Works like a charm! After implementing your solution, I also got my custom 404 pages to work. Thanks for the assistance!
    – Jenna
    Commented Sep 23, 2019 at 18:24
  • 3
    I added this in netlify.toml and it works! [[redirects]] from = "/*" to = "/index.html" status = 200
    – Hunter
    Commented Mar 21, 2020 at 3:34
  • 1
    can you explain why _redirects is the wrong answer given its the accepted answer with 8x ups?
    – notacorn
    Commented Jan 30, 2022 at 8:16
  • @notacorn no one said that _redirects is the wrong answer
    – nico
    Commented Feb 3, 2022 at 13:51
  • 1
    well, you said to remove it?
    – notacorn
    Commented Feb 3, 2022 at 14:58
11

I was having a similar issue so I created _redirects file in the public folder and put the following code

/* /index.html 200

build files again npm run build and worked for me resource for similar issue

7

If you ran into this issue for React Native Web, using an Expo-managed workflow, this solution fixed the problem:

  1. Create a netlify.toml in the project's root directory.

  2. Add the following code in the netlify.toml file:

    [[redirects]]
    from = "/*"
    to = "/index.html"
    status = 200
  1. Run the netlify deploy command in your terminal.
5

This is my _redirects file, which is in the /public folder with my index.html file:

_redirects in

/* /index.html 200

and then re-deploy your site in Netlify.

Thanks!

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented May 13, 2022 at 22:43
3

I had the same refresh issue in netlify. For me it was a series of changes. I had before my react configuration pointing to a subfolder (/sandbox/appfolder) to use in my hosting sandbox (I hope I can revert to that changing the parameters below). To be able to do a continuous deploy in netlify I did the following inspired in other answers. When using my own hosting sandbox, I didn't have the _redirects and the homepage pointed to the subfolder.

EDIT: to run from my site's subfolder I had to edit .htaccess to RewriteRule ^ /sandbox/myapp/index.html [L] and package.json to "homepage": "/sandbox/myapp"

in /package.json:

"homepage": "/",

in /public/.htaccess

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# Fallback all other routes to index.html    
RewriteRule ^ /index.html [L]

in my main component src/App.js:

<BrowserRouter basename = {process.env.PUBLIC_URL}>

in public/index.html

<base href="%PUBLIC_URL%/">

and finally as mentioned in /public/_redirects

/* /index.html 200
3

2022 Update:

If adding _redirects file did not work for me.(React JS)

For me the solution was to create netlify.toml file in the base directory of my react project. Then adding following.

[[redirects]] from = "/*" to = "/" status = 200

0
3

For me worked the next solution. First of all create a file on your public folder named _redirects (no extension, just pure text) and type -> /* /index.html 200 in it. Then in your package.json file set at very top the property { homepage: "YOUR PUBLIC URL", ...rest of the properties } and in the index.html file add <head>...<base href="YOUR PUBLIC URL">...</head>. Got the answer from this blog post, user called hrishikesh.

1

enter code hereUsing HashRouter instead of BrowserRouter solves the problem

import { HashRouter as Router, Switch, Route } from 'react-router-dom'
//instead of 
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
1

create _redirects in the root directory mention your app routes inside the _redirects file, for example: /home /terms-and-condition

that's it.

2
  • could you add how to mention app routes inside the _redirects file?
    – beniutek
    Commented Mar 4, 2021 at 10:03
  • Either in the Root or Public folder create a file named "_redirects" and add the following text: /* /index.html 200
    – TheVenice
    Commented Mar 4, 2021 at 17:41
1

try this

faced this same issue previously, founded that it was because of the proxy that I was using to connect to my backend server. Let's say the backend app is located at this URL example.com. So, instead of mentioning this as a proxy field in package.json, I would suggest putting the link in your functions only.

avoid this

{
  "name": "frontend",
  "version": "0.1.0",
  "proxy": "https://example.com",
  "private": true,
....
....
}

If, using redux then in put your backend url in actions with axios or fetch. (Also, try deleting the package-lock.json file and then push the code without it on your Github and then connect it to netifly and then re-deploy your site)

Example code (notice api call)

export const listArticles = () => async (dispatch, getState) => {
    try {
        dispatch({
            type: ARTICLES_LIST_REQUEST
        })

        // api call
        const { data } = await axios.get("https://example.com/api/articles/")

        dispatch({
            type: ARTICLES_LIST_SUCCESS,
            payload: data
        })

    } catch (error) {
        dispatch({
            type: ARTICLES_LIST_FAIL,
            payload: error.response && error.response.data.detail ? error.response.data.detail : error.message
        })
    }
}

My package.json file

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.10",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.21.1",
    "mdbreact": "^5.0.2",
    "react": "^17.0.2",
    "react-bootstrap": "^1.5.2",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.3",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "redux": "^4.0.5",
    "redux-devtools-extension": "^2.13.9",
    "redux-thunk": "^2.3.0",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
1

In my case I added the _redirects file and that did not work. I played with my CI settings again and in my build command I wrote CI = npm run build but then in the Public Directory field I wrote build and then triggered a redeploy and my site finally worked!

1

I tried the _redirects file and the netlify.toml updates but was still getting the 404. For me, the fix was to update the Build Settings on netlify.com. I think changing the Publish Directory to ./build was the fix:

netlify build settings

By the way, I followed some suggestions on stack/elsewhere to add a tag in my index.html file, and also to update the homepage in my package.json. Neither of these things helped and may have also messed up my fetch requests. (just in case anyone else was having similar issues)

1

Add a netlify.toml file in the root folder with the contents:

[[redirects]]
from = "/*"
to = "/"
status = 200

and it will work.

netlify.toml contents

0
  1. Go to /public folder.
  2. Create file called _redirects.
  3. Add the following code into the file: /* /index.html 200.
  4. Publish your app again. It should fix the Netlify page not found error.
-1

create-react-app documentation for deployment on Netlify mentioned to add _redirect file to avoid such issues:

Support for client-side routing:

To support pushState make sure to create a public/redirects file with the following rewrite rules:

/* /index.html 200

When you build the project, Create React App will place the public folder contents into the build ouput.

Reference: https://create-react-app.dev/docs/deployment/#netlify

1
  • 1
    Do not include pictures of text in your posts, it is not helpful. Text is text: type it out.
    – miken32
    Commented Sep 3, 2022 at 23:41
-4

From your index.js, just wrap your component with HashRouter instead of whatever that's there earlier. Don't forget to import HashRouter from react-router-dom.

It's magical.

Not the answer you're looking for? Browse other questions tagged or ask your own question.