6

I have a single page application + API I'm deploying to Vercel.

I'm currently trying to add some configuration in my vercel.json that:

  1. redirects calls not at the root (e.g. /login) to index.html` so that I can utilize the HTML History API (i.e. react-router's browser router)
  2. expect not for the /api endpoint where I have a few dynamic paths (e.g. /files/[fileId]/[checksum].ts)

How do I create a rewrite in Vercel that accomplishes this?

I've followed the advice from here: https://vercel.com/docs/configuration#routes/advanced/spa-fallback

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

However this does redirects API endpoints with dynamic paths to the index.html file too where I just want this to be the API.

Any ideas?

Rico Kahler
  • 17,616
  • 11
  • 59
  • 85

1 Answers1

5

You can use negative lookahead regex that check the url doesn't contains api.

/(?!api\/.*).*/
{
  "rewrites": [
    {
      "source": "/((?!api\/.*).*)",
      "destination": "/index.html"
    }
  ]
}
nouvist
  • 1,107
  • 10
  • 24
  • how do you create this route if you are using a custom root directoy folder ( like "src" ? ) thanks – Alberto S. Apr 23 '21 at 09:51
  • sorry, I having trouble understanding your question. you ask what if the backend is on custom directory, is that correct? – nouvist Apr 23 '21 at 09:58
  • So, I have my api folder under "./src/api". Since my serverless fn are under "./src", I defined the vercel project rood directory as "./src". In case, it is not clear for me how I should be creating the rewrites routes :-7 – Alberto S. Apr 23 '21 at 15:17
  • @AlbertoS. You stil could make the root is /, so then you create api/myapi.js that just import to your src/api/myapi.js. but you have to make "link" each routes. instead, you could use router library, and just have single entry, and then rewrites all api to that single entry (for example: api/index.js to src/api/index.js with api/* rewrites to api/index.js). because vercel is kind of not working if the api is on other directory. perhaps there is configuration for that. but me myself is using this method. – nouvist Aug 16 '22 at 11:07