A powerful and flexible Node.js module for serving static files (images, videos, stream videos range, pdf, documents etc) with ease. Jai Static offers seamless integration with any Node.js framework and provides fine-grained control over how your static assets are served.
- Features
- Quick Start
- Installation
- Usage Examples
- Configuration Options
- Advanced Usage
- Performance Optimization
- Security Considerations
- Troubleshooting
- License
- Author
- 🚀 Lightning-fast static file serving
- 🔧 Seamless integration with any Node.js framework
- ⚙️ Highly configurable for precise control
- 🗂️ Support for serving from multiple directories
- đź”’ Secure by default with customizable security options
- 📦 Efficient caching mechanisms
- 🎯 Content negotiation and partial content support
- 🔍 Extensible file discovery system
- đź“Ź File size limit control
- 🔣 Custom MIME type support
-
Install Jai Static:
npm install jai-static
-
Create a simple server (e.g.,
server.js
):const http = require('http'); const JaiStatic = require('jai-static'); const server = http.createServer(JaiStatic({ dir: './public' })); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
-
Create a
public
folder in your project root and add some files. -
Run your server:
node server.js
-
Visit
http://localhost:3000
in your browser to see your static files served!
Install Jai Static with npm:
npm install jai-static
const jaiServer = require('jai-server');
const app = jaiServer({
static: {
dir: `${__dirname}/public`,
basePath: '/static'
}
});
app.listen(3000, () => {
console.log('Jai Server listening on http://localhost:3000/ ...');
});
const express = require('express');
const JaiStatic = require('jai-static');
const app = express();
app.use('/assets', JaiStatic({
dir: `${__dirname}/public`,
maxAge: 3600,
index: ['index.html', 'index.htm'],
extensions: ['html', 'htm', 'json'],
lastModified: true
}));
app.listen(3000, () => {
console.log('Express server listening on http://localhost:3000/ ...');
});
const http = require('http');
const JaiStatic = require('jai-static');
const server = http.createServer(JaiStatic({
dir: `${__dirname}/public`,
maxAge: 3600,
headers: {
'X-Powered-By': 'Jai Static'
},
acceptRanges: true,
cacheControl: true
}));
server.listen(3000, () => {
console.log('HTTP server listening on http://localhost:3000/ ...');
});
Jai Static offers a wide range of configuration options to fine-tune its behavior:
Option | Type | Default | Description |
---|---|---|---|
dir |
string |
- | Destination folder path (Required) |
root |
string |
__dirname |
Root directory for serving files |
basePath |
string |
/ |
Base URL path for serving files |
urlPath |
string |
/ |
Alias for basePath |
dotfiles |
string |
'deny' |
How to treat dotfiles: 'allow', 'deny', or 'ignore' |
maxAge |
number |
3600 |
Browser cache max-age in seconds |
headers |
object |
{} |
Custom headers to set on the response |
lastModified |
boolean |
true |
Set the Last-Modified header |
etag |
boolean |
true |
Enable or disable ETag generation |
acceptRanges |
boolean |
true |
Enable or disable accepting byte ranges |
cacheControl |
boolean |
true |
Enable or disable setting Cache-Control header |
index |
string | string[] |
'index.html' |
Default file name(s) for directory requests |
extensions |
string[] |
['html', 'htm'] |
File extensions to try when not specified |
allowedExtensions |
string[] |
['*'] |
Allowed file extensions. Use ['*'] to allow all |
fallthrough |
boolean |
true |
Pass to next middleware if file not found |
immutable |
boolean |
false |
Add immutable directive to Cache-Control header |
defaultMimeType |
string |
'application/octet-stream' |
Default MIME type for files with unknown extensions |
mimeTypes |
object |
{} |
Custom MIME type mappings {"abc":"application/abc"} |
maxAllowedSize |
number |
- | Maximum allowed file size in bytes |
Let's explore each option with examples:
The directory from which to serve static files.
JaiStatic({ dir: './public' })
This will serve files from the 'public' folder in your project.
The root directory for resolving relative paths.
JaiStatic({ root: '/var/www', dir: 'html' })
This will serve files from '/var/www/html'.
The base URL path for serving files.
JaiStatic({ dir: './public', basePath: '/static' })
Files in './public' will be accessible under 'http://yourdomain.com/static/'.
How to treat dotfiles (files starting with a dot).
JaiStatic({ dir: './public', dotfiles: 'ignore' })
Options: 'allow' (serve dotfiles), 'deny' (return 403 error), 'ignore' (pretend they don't exist).
Browser cache max-age in seconds.
JaiStatic({ dir: './public', maxAge: 86400 }) // 1 day
This tells browsers to cache files for one day.
Custom headers to set on the response.
JaiStatic({
dir: './public',
headers: { 'X-Powered-By': 'Jai Static' }
})
This adds a custom header to all responses.
Set the Last-Modified header.
JaiStatic({ dir: './public', lastModified: false })
This disables the Last-Modified header, which can be useful for privacy.
Enable or disable ETag generation.
JaiStatic({ dir: './public', etag: false })
ETags help with caching, but disabling them can reduce server load.
Enable or disable accepting byte ranges.
JaiStatic({ dir: './public', acceptRanges: true })
This allows browsers to request parts of a file, useful for media streaming.
Enable or disable setting Cache-Control header.
JaiStatic({ dir: './public', cacheControl: false })
Disabling this gives you more control over caching behavior.
Default file name(s) for directory requests.
JaiStatic({ dir: './public', index: ['index.html', 'index.htm'] })
When a directory is requested, Jai Static will look for these files.
File extensions to try when not specified.
JaiStatic({ dir: './public', extensions: ['html', 'htm', 'json'] })
If '/page' is requested, Jai Static will look for 'page.html', 'page.htm', and 'page.json'.
Allowed file extensions.
JaiStatic({ dir: './public', allowedExtensions: ['html', 'css', 'js'] })
This restricts serving to only the specified file types.
Pass to next middleware if file not found.
JaiStatic({ dir: './public', fallthrough: false })
If false, Jai Static will send a 404 response instead of passing to the next middleware.
Add immutable directive to Cache-Control header.
JaiStatic({ dir: './public', immutable: true, maxAge: 31536000 })
This tells browsers that the file will never change, improving caching.
Default MIME type for files with unknown extensions.
JaiStatic({ dir: './public', defaultMimeType: 'application/octet-stream' })
This sets the content type for files with unrecognized extensions.
Custom MIME type mappings.
JaiStatic({
dir: './public',
mimeTypes: { 'dat': 'application/octet-stream' }
})
This allows you to set custom MIME types for specific file extensions.
Maximum allowed file size in bytes.
JaiStatic({ dir: './public', maxAllowedSize: 5 * 1024 * 1024 }) // 5MB
This prevents serving files larger than 5MB.
You can serve files from multiple directories by chaining middleware:
const express = require('express');
const JaiStatic = require('jai-static');
const app = express();
app.use('/assets', JaiStatic({ dir: './public/assets' }));
app.use('/images', JaiStatic({ dir: './public/images', maxAge: 86400 }));
app.use('/docs', JaiStatic({ dir: './public/documents', dotfiles: 'allow' }));
app.listen(3000);
Implement custom error handling by setting fallthrough
to false
and using a custom error handler:
const express = require('express');
const JaiStatic = require('jai-static');
const app = express();
app.use(JaiStatic({
dir: './public',
fallthrough: false
}));
app.use((err, req, res, next) => {
if (err.statusCode === 404) {
res.status(404).send('Custom 404: File not found');
} else {
next(err);
}
});
app.listen(3000);
To optimize performance with Jai Static:
- Enable caching by setting appropriate
maxAge
andimmutable
options. - Use
etag
for efficient cache validation. - Enable
acceptRanges
for partial content support. - Set
cacheControl
totrue
for better client-side caching.
Example of a performance-optimized configuration:
JaiStatic({
dir: './public',
maxAge: 86400 * 30, // 30 days
immutable: true,
etag: true,
acceptRanges: true,
cacheControl: true
})
Jai Static provides several security features:
- Dotfiles: By default, access to dotfiles is denied. You can change this with the
dotfiles
option. - Allowed Extensions: Use
allowedExtensions
to restrict which file types can be served. - Directory Traversal: Jai Static automatically prevents directory traversal attacks.
- File Size Limit: Use
maxAllowedSize
to prevent serving excessively large files.
Example of a security-focused configuration:
JaiStatic({
dir: './public',
dotfiles: 'deny',
allowedExtensions: ['html', 'css', 'js', 'png', 'jpg', 'gif'],
maxAllowedSize: 10 * 1024 * 1024, // 10MB limit
headers: {
'X-Frame-Options': 'SAMEORIGIN',
'X-XSS-Protection': '1; mode=block'
}
})
If you encounter issues:
- Check if the
dir
path is correct and accessible. - Ensure
basePath
matches your URL structure. - Verify that file permissions allow Node.js to read the files.
- Check for conflicting middleware in your application.
- If files aren't being served, check the
allowedExtensions
setting. - For large files, make sure they don't exceed the
maxAllowedSize
limit.
For more help, please open an issue on the GitHub repository.
Harpal Singh: @hsk11 . Website: Jaijs.org.
#jaijs #cdn #image-server #jai-static #static-files #stream-video #static-server #middleware