Ian
Ian

Reputation: 149

Escape static folder in Express

I set my /public folder as the static directory with express...

app.use(express.static('public'));

I need to include a script tag in my html linking to a file that is located outside of the public directory. (The script itself is a JS file that I installed with npm and is located in node-modules folder).

How do I escape the public directory in my html? I've tried all kinds of variations of ../ but it won't let me out of public.

Maybe there is a better way to handle this rather than trying to link to a script that is located in my node-modules folder?

Any help is appreciated

Upvotes: 0

Views: 238

Answers (2)

jfriend00
jfriend00

Reputation: 707326

You don't escape the public directory with express.static(). That is done for security reasons so people can't make up URLs and go poking around your server hard drive.

Instead, you need to make a new route for that script file. If it's a single file and it's in a node_modules directory below where your source file is, you can make just a simple single route:

app.get("/myscript.js", function(req, res) {
     res.sendFile(path.join(__dirname, "node_modules/someModule/somescript.js"));
});

Note in this example that the URL you use does not have to be the same as the file's actual name. Unlike with express.static(), they are independent when making a custom route like this so you can make the URL filename be whatever you want as long as it doesn't conflict with other routes you have.


If there are multiple files in that same directory that you want public, but you don't want others in that directory hierarchy to be public, then you can't really use another express.static() to only target a couple files in that directory so you'd either have to move the public files to their own directory or make an individual route for each file.

Here are some other examples:

How to include scripts located inside the node_modules folder?

How to add static file from `node_modules` after declare the `public` as static in express?

Upvotes: 1

You could download just the script and then store it in your public folder.

Upvotes: 0

Related Questions