Is it possible to give a custom path to the `/static` directory using React and Express?

Viewed 117

Edit

To anyone coming here in the future, I solved this problem by indicating a value for PUBLIC_URL in my .env file.

In my case, I set PUBLIC_URL=/ui and now the static assets are being served from .../ui/static/...


Whenever I build my app and launch it, the browser requests content from the static directory, such as this:

img

Is it possible to somehow change this? I took a look here, but I didn't have any luck. I tried different combinations of express.static(. . .) to no avail.

Instead of http:///static/bundle123, I want it to request http:///custom/static/bundle123.

I've tried moving my build/static directory into build/custom/static and doing something like this, but it didn't work:

app.use('/static', express.static(path.join(__dirname, './custom')))

What am I doing wrong?

1 Answers

The first argument determines the URL path and the second part determines where the files are located on the file system.

So if your static files are located in the public directory (or in sub directories) and you want to access then on the https://.../static URL, you can use:

app.use('/static', express.static(path.join(__dirname, 'public')));

In your case, assuming you run the server from the build directory, using the following should work:

app.use('/custom/static', express.static(path.join(__dirname, 'static')));

Now if you request an URL https:///custom/static/foo Express will look for a file named foo in the static folder.

Related