Vercel Rewrite: SPA Fallback except for API endpoint

Viewed 1709

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?

1 Answers

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

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