typescriptwebpackvercel

vercel - how to return index.html on every route change?


i have a problem. i created a url shortener website with typescript and it is a single page website but the route can be changed. in this project i use webpack and for dev server i use webpack-dev-server and to return index.html for almost all routes, i wrote this code in webpack.config.js:

  devServer: {
    static: {
      directory: path.join(__dirname, "dist"),
    },
    compress: true,
    proxy: {
      "/**": {
        target: "/index.html",
        secure: false,
        bypass: function (req, res, opt) {
          if (
            req.path.indexOf("/img/") !== -1 ||
            req.path.indexOf("/public/") !== -1
          ) {
            return "/";
          }

          if (req.path.indexOf("/build.css") !== -1) {
            return "/build.css";
          }

          if (req.headers.accept.indexOf("html") !== -1) {
            return "/index.html";
          } else return;
        },
      },
    },
  }

now i want to enable this(returning index.html on every route change) for the vercel server of app. at this time, when i change the route, i will get a 404 page. but i want to get index.html. i searched a lot to achieve what i want and i tested some ways but i couldnt do what i want. i created a file called vercel.json at the root folder of my project and i tried redirects, rewrites and routes. i dont know, perhaps i used these properties wrong. so how can i do this? thanks for helping. i tried these configs and etc:

{
  "redirects": [{ "source": "/[^.]+", "destination": "/" }],
  "rewrites": [{ "source": "/[^.]+", "destination": "/" }]
}


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

Solution

  • I found that I shouldn't have used redirects and routes property in vercel.json to achieve what I want. I should have used rewrites instead. One other thing is that I used rewrites wrong. I should have used it like this:

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

    According to the docs, this works "because precedence is given to the filesystem prior to rewrites being applied".