28

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

Andrew Stegmaier
  • 3,429
  • 2
  • 14
  • 26

11 Answers11

97

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

broofa
  • 37,461
  • 11
  • 73
  • 73
surbina
  • 1,094
  • 8
  • 5
  • 2
    I was placing my vercel.json where the app is but it must be in the repo root – Fabio Milheiro Dec 30 '21 at 00:50
  • @FabioMilheiro I am struggling to find documentation on where to put the vercel.json in any kinda monorepo. – hevans900 Jul 12 '22 at 16:50
  • 3
    This worked perfectly for me with react-router. Thanks! – Victor Eke Aug 10 '22 at 14:54
  • This one seems to not work with dynamic API routes, like /api/foo/[bar].js – Tayyab Ferozi Jan 30 '23 at 15:02
  • 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! – Benjamin Mar 25 '23 at 16:51
  • 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) – Benjamin Mar 25 '23 at 16:51
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!

Cristian Macedo
  • 151
  • 1
  • 7
2

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 .

Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76
1

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": "/"
    }
  ]
}
Ayub
  • 11
  • 1
1

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

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

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]
andriusain
  • 1,211
  • 10
  • 18
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.

Andrew
  • 3,825
  • 4
  • 30
  • 44
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.

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

Bravado
  • 137
  • 9
0

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

blank1729
  • 1
  • 1
-2

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