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

Time:09-21

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 }]
}

CodePudding user response:

i found that i shouldnt 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" //here i tested / and it worked too }]
}

i hope my solution helps you.

  • Related