serve-handler
serve-handler copied to clipboard
Repeated segments should be supported by passing array to pathToRegExp.compile
Context
- Serving react app under
/app
prefix e.g.example.com/app/products
- Installed
serve
and customized withserve.json
- Used
"homepage":"/app"
inpackage.json
according to CRA docs - Asset path is correctly inferred and generated but
serve
is not serving asset files correctly underbuild/static/...
serve.json
used for above:
{
"public": "build",
"rewrites": [
{ "source": "/app/static/:segment*", "destination": "/static/:segment*" },
{ "source": "/app", "destination": "/index.html"}.
{ "source": "/app/**", "destination": "/index.html"}
]
}
After some debugging, I identified the issue to be in toTarget
. We are not passing in array of parameters when we are compiling the valid path https://github.com/zeit/serve-handler/blob/e7c4e42a63e9cd59b43256bb4ca04a22a5f77994/src/index.js#L79-L86
We should be passing array according to the docs(v2.2.1 that we are using). If not it treats the whole string as a single segment value and encodes /
.
Debug logs:
// applyRewrites
relativePath: "/app/static/css/2.c7bb94bc.chunk.css" //argument
rewrittenPath: "/app/%2Fcss%2F2.c7bb94bc.chunk.css" // return value
// toTarget
props: {
"segment": "/css/2.c7bb94bc.chunk.css"
}
normalizedDest: "/static/:segment*"
toPath(props): "/static/%2Fcss%2F2.c7bb94bc.chunk.css"
This should be easily fixed by doing a split by /
when we are setting the props i.e. props[name] = results[index + 1].split("/");
This will fix repeated segment for redirects as well.
Documents should also be updated with instructions on how to use repeated segment. (I figured out during debugging that destination needs *
as well else the compile function will complain that the url built does not match the destination pattern 😅)
Not sure if my proposed solution is correct but it works locally for me so far. I am happy to work on this with tests and docs for repeated segment