How do you change the express static directories? - node.js

I am working on a development platform, I have code similar to the following:
app.use('/public', express.static( config.directory.public ));
The issue is that there are many (100s) of projects each with its own directory structure. The project will be selected via the URL:
http://localhost/dev/accounts
Where accounts is a project with its own directory tree and static public directory.
I do not want to run a separate copy of node for each project. Once a project has been selected via the URL then express needs to be reconfigured to serve files for that request.
However, that approach is probably not feasible because we may be working on many projects at the same time. So every request for static files would have to be processed according to the project URL. It seems to negate the benefit of static directories.
I think what I am after is a way to put variables into the directory path
http://localhost/dev/accounts
Would set a variable called prj = "accounts" and then somehow set express so that the root directory is "c:\projects\" + prj + "\public".
If I simply issue a new app.use(..) statement for every request I imagine bad things will happen.
Maybe I am better off just manually reading the file contents for each static request and sending the contents back.
Is there another way to approach this problem?

I'm not sure if I understood your question correctly, but express serves static files in file directories automatically for you. If you have a bunch of projects in some 'path/to/public' folder, you just need to do something like
app.use('/', express.static( __dirname + '/public' ));
That way, you just need to type some url like
http://localhost/project1
or
http://localhost/project2

Related

How to host SPA files and embed too with axum and rust-embed

I'm having hard time understanding how to embed SPA (single page application) files with rust-embed and axum.
I have no trouble without rust-embed using a single line of code with axum (from here):
app.fallback(get_service(ServeDir::new("./app/static")).handle_error(error_handler))
It works because all files are correctly downloaded. But:
FIRST PROBLEM
What is missing for a properly SPA handling is the redirect on the index.html if for example the user reloads the page on a SPA nested route.
Example: I'm on the page: /home/customers which is not a file nor a dir but just a fake javascript route and if I reload the page axum gives me 404 (Not found).
SECOND PROBLEM
I need to embed those files in my final executable. In Golang this is "native" using embed: directive.
I saw that in Rust this is well done with rust-embed but I cannot complete my task for SPA.
The need is that every path typed by the user (and that is not an existent file such as .js or .css which obviously must be downloaded by the browser) leads to the "index.html" file in the root of my static dir.
If I use the example axum code I can see the route:
.route("/dist/*file", static_handler.into_service())
which has /dist/*file and I don't need that /dist because the index.html calls many files with custom paths, such as /_works, menu, images.
If I remove the dist part I get this error:
thread 'main' panicked at 'Invalid route: insertion failed due to conflict with previously registered route: /index.html'
Can you help me understand how to properly accomplish this task?
Thanks.
I had a similar issue, building with Vue and Axum/Rust.
Here's how I solved Problem one
Install the tower_http crate
use axum::routing::get_service to serve the build SPA.
//example implementation
...
//static file mounting
let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("views");
let static_files_service = get_service(
ServeDir::new(assets_dir).append_index_html_on_directories(true),
)
.handle_error(|error: std::io::Error| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
)
});
...
Mount the static file rendering
//mount the app routes and middleware
let app = Router::new()
.fallback(static_files_service)
.nest("/api/v1/", routes::root::router())
.layer(cors)
.layer(TraceLayer::new_for_http())
.layer(Extension(database));
Check out the full source code here. Another thing is, Axum seems to have breaking changes in subsequent versions as I found out here, so you might need to check the doc/example that corresponds to the version of Axum you are using :)

Next.JS security of directory structure and JSON secrets

I have a security question regarding the access of Next.JS directories, and their access requirements. I have a root folder that has my pages, public, src, styles, models folders. In the src folder I have a settings.json file that is a empty JavaScript object. The idea is that settings would be added to this file and accessed by api routes, to check settings that could be modified on this settings.json file... What I am wondering is if the client can actually somehow just read/access the src directory and get the settings.json file. I want to put secret key's here that way I can easily change secret keys without having to restart my server. So I could just update the secret key live, and have it applied to the settings.json file. Then the update would be live immediately and I don't have to change the environment variables and restart the server.
Is it safe to keep and use a json file in the src directory to store confidential data? If not, is there a way to keep and use a json file for this purpose?
Thanks for the help and info.
As juliomalves pointed out client code won't be able to access a directory or file that you have on the server with the exception of the public directory.
Next gives you the ability to serve static assets from [root]/public as documented here
Note: Only assets that are in the public directory at build time will be served by Next.js.
If this directory is ever renamed, these assets are no longer available from a client.
Note: Don't name the public directory anything else. The name cannot be changed and is the only directory used to serve static assets.
"I put a settings.json file right next to that .env file and required it in an api route, could the client somehow download that settings.json file without me purposely sending them the contents/file itself?"
The only way information can be served from an api route is by expressly creating a route to call res[ponse].send() (or res.json()) with data imported from that file. Api routes are not ever bundled on the client side and only ever exist on the server as noted here.
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.
"What I am wondering is if the client can actually somehow just read/access the src directory and get the settings.json file."
As noted above only assets in the /public directory are accessible as files by path. Directories are never accessible in Next as static assets. This is even pointed out in the source code.
send(req, path)
.on('directory', () => {
// We don't allow directories to be read.
const err: any = new Error('No directory access')
err.code = 'ENOENT'
reject(err)
})

React dynamic image importing in development

I am building a React application which needs to display images dynamically which are stored, by the thousands, on a server-side file system. All of my attempts to successfully implement this have failed, including many which were taken from responses to similar questions.
Some details:
I used create-react-app to initialize my application. I am running in development mode (have not run npm-build). I'm using Express.js (Node.js) as a web-server, which I interact with through a proxy (only '/api' http requests use the proxy). My js code which attempts to 'require' the images is in the 'src' folder. The images are located in an 'images' folder in the default 'public' folder.
I thought I had found the solution when reading this page from create-react-app, as it states to use the public folder when 'You have thousands of images and need to dynamically reference their paths'. The page further instructs to use '%PUBLIC_URL%' or 'process.env.PUBLIC_URL' to access the 'public' folder. When using either of these I receive an 'Error: Cannot find module' message. Upon checking I notice that 'process.env.PUBLIC_URL' contains an empty string, and quickly notice that PUBLIC_URL is ignored in development mode.
I find this to be tremendously confusing, given that the 'Using the Public Folder' page is apparently describing the development phase of production, and yet it advises the use of something which is meaningless during development. Adding to my confusion, it appears as if the contents of that page resolved the issue for nearly all of those who have encountered a similar requirement in the past (example: 1, example: 2; both fail for me). Likewise, all attempts to to construct relative paths to the 'public' folder from the 'src' folder have yielded error messages. Failed code example:
let img = process.env.PUBLIC_URL + '/images/Team.jpg';
<img src={require(`${img}`)} alt="X" />
Error: Cannot find module '/images/Team.jpg'
I never imagined showing images in React would be so difficult. Any help is truly very much appreciated.
I think you are correct, you just don't need the require, return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; as you can see their docs
If you open in your browser http://localhost:PORT/images/Team.jpg that should open.
That's the reason process.env.PUBLIC_URL is empty in development, because they resolve everything inside this folder directly.

Securing files in Google Cloud app engine (NodeJS)

I have created a small web application with NodeJS Express. Basically a webserver that has a 'webserver.properties' file. With a very basic app.yaml file.
After deploying it to Google Cloud by use of 'gcloud app deploy' I get the everything up and running.
However...when I open the following URL in the browser: https://webserverurl.com/webserver.properties , the webserver.properties file can be approached and is in turn downloaded immediately.
How can I prevent this from happening and make sure that such properties files are inaccessible from outside?
The problem is that when you use this line:
app.use('/', express.static(__dirname + '/'));
you are giving access to your root directory. See this for a definition of __dirname. If you want to give access to a specific folder you can do this:
Lets say your root directory is src and you fave a dir with static files called src/myfiles. In order to give acces to files in myfiles you can use this line:
app.use('/mypathname', express.static('myfiles'));
where:
'/mypathname' is the part pertaining your URL. In your case it would be https://webserverurl.com/mypathname/any-file-name.jpg
express.static('myfiles') is the name of your local dir.
See this guide.
Hope this helps

Displaying images from node(server) to angular 2?

I'm uploading files from Angular 2 with ngx-uploader and storing them on backend (nodejs/feathers) with multer. Now I'm having trouble to reach and display them, for now im just trying to display image, but actually i just need to see how paths work so i can reach the .pdf files.
As a file path im getting this: resources\\uploads\\quality-docs\\FILENAME so i tried to reach them like this: http://localhost:3030/resources/uploads/quality-docs/FILENAME but it doesnt work, it gives me 404. Just realised when i put files in static, public folder, i can reach it like http://localhost:3030/FILENAME ... but is there a way for it to not be in public?
This is how my backend structure looks like:
Any ideas/sugestions are welcome, is this even a right way to go? Plus if any of you have idea how to delete files from server?
Assuming that you are using express in your node app, you need to include a static route to the resources/uploads directory (express static routes) like the following:
app.use(express.static('resources/uploads'))
For deleting files from a node application use unlink fs.unlink

Resources