Protect static files using jwt authentication Protect static files using jwt authentication express express

Protect static files using jwt authentication


Most often it is unnecessary to protect static assets (e.g. .html, .css, .png, .js, etc.) files and protecting your API endpoints would suffice.

However, if you retrieve the assets (e.g. HTML fragments for an SPA) using AJAX, then you can pass the JWT as a header inside your request and in the backend your web server can inspect the header and return the HTML fragment only if the current user is authorized to access it.

Also you can store the JWT inside local storage and configure your AJAX library to get the token from the local storage and add it to your requests before sending them to the server.


I don't know what questions you exactly means, but I think you want to protect specify static files like personal images or some else.

If like my think, you can .use(jwt) to protect your specify static files before .use(static) files.

for example:

const express = require("express");const app = express();const exjwt = require("express-jwt");const STATIC_PATH = path.join(process.cwd(), "src", "static");app  .use("/images", exjwt({ secret: "SECRET" }))  .use(express.static(STATIC_PATH))app.get('/', (req, res) => {   res.send('...') });app.listen(3000);

Like this, user can request your static files except static images files.