Why does react-router not works at vercel?
Asked Answered
B

17

44

I am trying to publish a serverless web to vercel. I want to use react-router and this works good on my computer but when I deploy it It doesn't works Can somebody help me?

(I want to do it without server)

// My main code
import React from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'

import Main from './routes/Main'
import Tos from './routes/Tos'
import Privacy from './routes/Privacy'
import NotFound from './routes/NotFound'
import Recruit from './routes/Recruit'

const App = () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route exact path = '/' component = {Main} />
                <Route exact path = '/recruit' component = {Recruit} />
                <Route exact path = '/tos' component = {Tos} />
                <Route exact path = '/privacy' component = {Privacy} />
                <Route component = {NotFound} />
            </Switch>
        </BrowserRouter>
    )
}

export default App

Result

Bathometer answered 13/11, 2020 at 3:20 Comment(0)
P
153

Add a vercel.json file at the root of your project, and use "rewrites" to rewrite all incoming paths to refer to your index path.

For example:

{
  "rewrites":  [
    {"source": "/(.*)", "destination": "/"}
  ]
}

Check here for further information: https://vercel.com/docs/configuration#project/rewrites

Paradies answered 9/1, 2021 at 15:5 Comment(8)
I was placing my vercel.json where the app is but it must be in the repo root πŸ‘ – Tedious
@FabioMilheiro I am struggling to find documentation on where to put the vercel.json in any kinda monorepo. – Dumuzi
This worked perfectly for me with react-router. Thanks! – Skyjack
This one seems to not work with dynamic API routes, like /api/foo/[bar].js – Kazak
Incredible, this is exactly what I was looking for. I was considering spinning up a tiny express server to host my app or migrate to a framework like Next.js. This solved the issue in two lines of JSON. Thank you! – Latvia
Another note: the vercel.json must be where the "root dir" is defined (you can find this in your project settings on the Vercel website) – Latvia
I use Vite to start my react project and adding above vercel.json while fixing the problem on Vercel causes my app to crash on localhost. If I remove vercel.json then everything works on localhost even after a reloading of browser. It seems vite does the rewriting itself and adding vercel.json rewrites causes some kind of conflict with Vite's handling of rewrite. Anybody ran into this? – Larch
There are the errors I get in console when I run my Vite React project on localhost after adding the suggested solution: GET localhost:3000/@vite/client net::ERR_ABORTED 404 (Not Found) GET localhost:3000/src/main.tsx net::ERR_ABORTED 404 (Not Found) GET localhost:3000/@react-refresh net::ERR_ABORTED 404 (Not Found) – Larch
I
13

Specifying each Route

In order to make the React Router work in Vercel I had to specify each route in the vercel.json file, as mentioned in Surbina's answer. (Thanks btw, I used this solution for a quite some time)

{
  "routes": [
    { "src": "/", "dest": "/" },
    { "src": "/recruit", "dest": "/" }
    { "src": "/tos", "dest": "/" }
    // ....
  ]
}

But this may not be optimal depending on how many routes your application has, and honestly sometimes I forget to add new routes.

The "Match all" regex problem in Vercel

I tried the "match all" Regex as the source route [{ "src": "/*", "dest": "/" }], like I used to do in other hosting services, but for some Reason, Vercel server uses this routing for all requests, even when index.html needs to request a file like bundle.js, breaking the application.

Solution: Match routes but ignore files

And the solution I've found is using a Regex that matches all routes, except for routes that include a dot (.), which are usually files, like bundle.js. Then you can request a url like /recruit and it gets routed to / since it doesn't have a dot.

The regex is /[^.]+ (Turns into ^/[^.]+$ on Vercel).

Please note that this is a very simple Regex and may not cover all cases, however, I haven't got any issues with it to the moment of this comment.

So my vercel.json file looks like this:

{
  "routes": [{ "src": "/[^.]+", "dest": "/", "status": 200 }]
}

I hope it is useful for you!

Iredale answered 9/4, 2021 at 1:38 Comment(0)
G
4

Simply add this to your vercel.json, this will route all your routes to the index.html except for the js file

{
  "routes": [
    {
      "src": "/[^.]+",
      "dest": "/"
    }
  ]
}
Giliane answered 9/4, 2021 at 23:49 Comment(0)
W
3

In vercel hosting service you can either deploy the whole project by selecting create-react-app in framework preset :

create-react-app

or you can deploy only the build folder after you've built the project by running npm run build and select Other as Framework preset :

other

Note

If you're using react-router-dom with BrowserRouter you should have vercel.json file at the root of your project folder or your build folder :

{
  "rewrites": [
    {
      "source": "/((?!api/.*).*)",
      "destination": "/index.html"
    }
  ]
}

This configuration will prevent your web application to have 404 error when you refresh the page or when you open other routes .

Hope it helped you .

Wilinski answered 23/9, 2021 at 17:9 Comment(0)
R
2

create vercel.json file in root directory and paste the code

{
   "rewrites":  [
       {"source": "/(.*)", "destination": "/"}
    ]
}
Riddick answered 7/4, 2023 at 9:0 Comment(0)
R
1

Here is something that worked for me

{
  "rewrites": [
    {
      "source": "/:path((?!api/).*)",
      "destination": "/index.html"
    },
    {
      "source": "/:path(api/.*)",
      "destination": "/api"
    }
  ]
}

docs : https://vercel.com/docs/concepts/projects/project-configuration#rewrites

Rostock answered 10/6, 2023 at 2:5 Comment(0)
G
1

Since I had the same issue and none of the above fixed it, I created a medium post to explain how to solve this issue.

Step 1: In the root of your project, you need a vercel.json file. This is the configuration file Vercel uses to understand how to handle your project.

Step 2: Update the vercel.json file with the following content: (this vercel.json file is for a frontend React app with a nodejs backend)

{
  "version": 2,
  "builds": [
    {
      "src": "api/index.js",
      "use": "@vercel/node"
    },
    {
      "src": "client/package.json",
      "use": "@vercel/static-build",
      "config": {
        "distDir": "build"
      }
    }
  ],
  "routes": [
    {
      "src": "/api/(.*)",
      "dest": "/api/index.js"
    },
    {
      "src": "^/static/(.*)",
      "dest": "/client/static/$1"
    },
    {
       "src": "/(.*)\\.png",
       "dest": "/client/$1.png"
     },
    {
      "src": "/(.*)",
      "dest": "/client/index.html"
    }
  ]
}

Here’s how this configuration works:

"src": "api/index.js" tells Vercel to use @vercel/node to handle serverless functions in the /api directory. "src": "client/package.json" tells Vercel to use @vercel/static-build to build your React App located in the /client directory. "src": "/api/(.)", "dest": "/api/index.js" handles all API requests and directs them to the appropriate serverless function under the /api directory. "src": "^/static/(.)", "dest": "/client/static/$1" ensures that static assets under the /static directory are served correctly. "src": "/(.*)", "dest": "/client/index.html" handles all other routes by serving the index.html file. This allows React Router to take over and render the appropriate component based on the route.

Source: https://medium.com/@simonsruggi/fixing-react-router-issues-on-vercel-how-to-handle-client-side-routing-and-404-errors-f607aa0c9bfe

Gadson answered 21/7, 2023 at 12:53 Comment(2)
Please don't post answers for self-promotion of your website. Instead, put the relevant details that answer the questions here. – Rubin
Changed my answer. Thanks – Gadson
T
0

It sounds like Vercel is looking in the wrong place for your files. Check the "homepage" field in your package.json; I've found that they're finicky, and sometimes what works when using localhost doesn't work on a Vercel deployment. If you don't have a `"homepage" field, start by adding

"name": "my-app",
"homepage": ".",
...

in package.json. That usually works for me, but if it doesn't, try the actual url of your deployment, i.e., https://something.vercel.app. I have had to do that for certain setups.

If that still doesn't work, check the Network tab in devtools and find your request, and check what url it's actually looking for resources with. That might give you some clues.

Than answered 19/11, 2020 at 22:42 Comment(0)
K
0

I'm using Create React App and react-scripts for building the project and I had an issue similar issue. The problem was the sub-routes content wasn't loading when I click browser refresh on the vercel's deployed site but locally it works fine.

ex. if you go directly to this sub route it would failed

https://mysite/top/second

It turns out that the problem is in my package.json I had "homepage": "." I simply fixed it by changing it "homepage": "" (removing the dot)

react-scripts build will read package.json homepage property and it will append the value from homepage to all the paths that links the js and css bundled code.

Kneedeep answered 20/4, 2022 at 19:22 Comment(0)
O
0

You can also run (your production build) like

yarn serve build -s

-s option redirects all not found paths to index.html, so you don't even need the serve.json/vercel.json file

Osy answered 28/10, 2022 at 14:6 Comment(0)
F
0

{
  "routes": [
    { "src": "/[^.]+", "dest": "/", "status": 200 }
  ]
}

This solution worked and the redirects worked.

I also tried the first solution where there are too many infinite redirects.

Fading answered 6/9, 2023 at 16:27 Comment(0)
B
0

I don't have any reputation to answer directly to Andrew, but this is some very important information! Assigning the vercel homepage URL to the homepage was what worked for me! I was having a problem where any dynamic route (using params) would not be recognized in vercel production build, yet working flawlessly in localhost. After many tries, this is what worked for me!

package.json:

{
name: 'yourapp',
homepage: 'https://yourapp.vercel.app'
/*...*/
}
Busy answered 18/10, 2023 at 17:22 Comment(0)
E
0

if you having same issue try this:

create vercel.json in your project route and write this code. This code work for especially you use react router

{ "routes": [{ "src": "/[^.]+", "dest": "/", "status": 200 }] }
Endolymph answered 27/10, 2023 at 5:34 Comment(0)
K
0

This is the best answer I got. So when ever you refereshed on any route like "/admin" so it first take you to "/" route and then from your code, allow user to Navigate to Admin.

{
  "routes": [
    { "src": "/[^.]+", "dest": "/", "status": 200 }
  ]
}
Kristine answered 12/11, 2023 at 16:56 Comment(0)
G
0

Yes I also faced the same problem, let's see the best solution for this.

Here I have some routes in App.js file

<BrowserRouter>
  <Routes>
    <Route path="/login" element={<SignIn />} />
    <Route path="/login/phone-verification" element={<PhoneVerification 
     />} />
    <Route path="/" element={<LandingPage />} />
    <Route path="/topics" element={<LandingTopics />} />
  </Routes>

</BrowserRouter>

For this routes need to fix the issue create vercel.json file at root projects and add following objects in that file

{
"routes": [
  { "src": "/login", "dest": "/" },
  { "src": "/login/phone-verification", "dest": "/" },
  { "src": "/topics", "dest": "/" },
  { "src": "/", "dest": "/" }
]
}

You can change according your routes.

Gave answered 4/4, 2024 at 9:25 Comment(0)
A
0

In my case I added the following code inside vercel.json in project folder(not inside src)

{
 "rewrites": [{ "source": "/(.*)", 
 "destination": "/" }]
}
Agapanthus answered 16/7, 2024 at 19:23 Comment(0)
M
-1

Maybe you need the server to redirect all requests to index.html. If Apache then you can use mod_rewrite and you would need some code like this:

RewriteCond %{REQUEST_URI} !^/index\.html
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/.*$ /index.html [L,PT]
Menorrhagia answered 13/11, 2020 at 3:29 Comment(3)
I want to do it without server – Bathometer
you should change your question then, @kiki7000 – Lindyline
Okay Edited the question – Bathometer

© 2022 - 2025 β€” McMap. All rights reserved.