A lightweight, token-authenticated JSON file server with real-time WebSocket support. Store and retrieve JSON data files with built-in access control, rate limiting, and comprehensive logging.
- RESTful API: Simple HTTP endpoints for GET, POST (create/update), and DELETE operations
- Token-based Authentication: Secure API access using API tokens with per-app isolation
- Real-time Updates: WebSocket support for live notifications when files change
- Rate Limiting: Built-in protection against abuse with configurable rate limits
- Easy to use: Create, save or get a json. you can watch for changes on a given json.
- Error Handling: Standardized error responses with clear error codes and messages
- Data Validation: Request validation and path sanitization for security
- ES Modules: Modern JavaScript with ES6 modules support
- Test Coverage: Full test suite with Jest and Supertest
| Method | Path | Description | Auth Required | Returns |
|---|---|---|---|---|
| GET | /*path |
Retrieve JSON file | Yes | File content or 404 |
| POST | /*path |
Create or update JSON file | Yes | Status and path |
| DELETE | /*path |
Delete JSON file | Yes | Status and path |
| WS | /*path |
Subscribe to file changes | Yes | Real-time updates |
You can run my-json-server using Docker:
- Pull the image
docker pull ijimiguel/my-json-server:latest(Or specify a version tag, e.g. :1.0.2)
- Run the container with necessary environment variables and volume mounts:
# docker-compose.yml
version: '3.9'
services:
app:
image: ijimiguel/my-json-server:latest
user: '${UID}:${GID}' # Optional: only if you want to match host user
ports:
- '4123:3000' # external:internal, since CONFIG.PORT defaults to 3000
environment:
ALLOWED_ORIGIN: '*'
RATE_LIMIT_WINDOW_MS: 60000
RATE_LIMIT_MAX: 100
volumes:
- ./data:/usr/src/app/data # writable local folder for app data
- ./myApiKeys.json:/usr/src/app/apiKeys.json:ro # user-provided token file (read-only)
restart: always- Run docker with user rights
# make sure to create the data folder and set the correct permissions
mkdir -p ./data
chown $(id -u):$(id -g) ./data
export UID=$(id -u)
export GID=$(id -g)
docker-compose up -dThis will:
- Map port 3000 from the container to your host
- Store the jsons on ./data host folder
- Get the api keys from host in ./myApiKeys.json
- Set the required environment variables
- To stop
docker-compose down- Node.js 18.x or higher
- npm 9.x or higher
- Clone the repository:
git clone https://github.com/JGEsteves89/my-json-server.git
cd my-json-server- If you need to set the remote origin manually (e.g., for existing repositories):
git remote add origin https://github.com/JGEsteves89/my-json-server.git- Install dependencies:
npm installnpm startThe server will start on http://localhost:3000 by default.
npm test# Check for lint errors
npm run lint
# Fix lint errors automatically
npm run lint:fix
# Format code with Prettier
npm run formatAll endpoints require the x-api-token header with a valid API token.
Retrieve the JSON content of a file.
Request:
curl -H "x-api-token: YOUR_TOKEN" http://localhost:3000/mydataResponse (200 OK):
{
"key": "value",
"nested": {
"data": "example"
}
}Response (404 Not Found):
{
"error": "NOT_FOUND",
"message": "The requested file could not be found",
"statusCode": 404
}Create or update a JSON file at the specified path.
Request:
curl -X POST \
-H "x-api-token: YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"key":"value"}' \
http://localhost:3000/mydataResponse (200 OK):
{
"status": "created",
"path": "/mydata"
}Or if the file already exists:
{
"status": "updated",
"path": "/mydata"
}Response (400 Bad Request):
{
"error": "VALIDATION_ERROR",
"message": "Request body must be valid JSON",
"statusCode": 400
}Delete a JSON file at the specified path.
Request:
curl -X DELETE \
-H "x-api-token: YOUR_TOKEN" \
http://localhost:3000/mydataResponse (200 OK):
{
"status": "deleted",
"path": "/mydata"
}Response (404 Not Found):
{
"error": "NOT_FOUND",
"message": "The requested file could not be found",
"statusCode": 404
}Connect to the WebSocket server to receive real-time updates when files change.
Connect:
const ws = new WebSocket(`ws://localhost:3000/mydata`, {
headers: { 'x-api-token': 'YOUR_TOKEN' },
});
ws.addEventListener('message', (event) => {
const { path, data } = JSON.parse(event.data);
console.log(`File ${path} changed:`, data);
});Message Format:
{
"path": "/mydata",
"data": {
"key": "value"
}
}| Method | Path | Description | Auth Required | Returns |
|---|---|---|---|---|
| GET | /*path |
Retrieve JSON file | Yes | File content or 404 |
| POST | /*path |
Create or update JSON file | Yes | Status and path |
| DELETE | /*path |
Delete JSON file | Yes | Status and path |
| WS | /*path |
Subscribe to file changes | Yes | Real-time updates |
The API returns standardized error responses with the following codes:
| Error Code | HTTP Status | Description |
|---|---|---|
FORBIDDEN |
403 | Invalid or missing API token |
NOT_FOUND |
404 | Requested file does not exist |
VALIDATION_ERROR |
400 | Invalid path or request body |
INTERNAL_ERROR |
500 | Server error (check logs) |
my-json-server/
├── src/
│ ├── server.js # Express server setup
│ ├── routes.js # API endpoint handlers
│ ├── apiTokenMiddleware.js # Token validation middleware
│ ├── errorHandler.js # Global error handler
│ ├── errors.js # Error class definitions
│ ├── auth.js # Authentication utilities
│ ├── config.js # Configuration management
│ ├── logger.js # Logging setup with Winston
│ ├── utils.js # Utility functions
│ └── websocket.js # WebSocket manager
├── tests/
│ └── server.test.js # Test suite
├── data/ # Default data storage directory
├── package.json # Project metadata
└── README.md # This file
Contributions are welcome and encouraged! Please follow these guidelines:
-
Fork the repository and create a feature branch
git checkout -b feature/your-feature-name
-
Make your changes and ensure code quality
npm run lint:fix npm run format
-
Add or update tests for new functionality
npm test -
Commit with clear messages
git commit -m "feat: add new feature" -
Push to your branch and create a Pull Request
git push origin feature/your-feature-name
- Use ESLint for code quality:
npm run lint - Use Prettier for formatting:
npm run format - Follow the existing code patterns and conventions
- Write tests for new features
This project is licensed under the MIT License - see below for details.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Attribution: When using this software, please acknowledge the original authors and include a reference to this project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check existing documentation
- Review test cases for usage examples
- 1.0.8 - Fixed docker folder permissions and instructions
- 1.0.5 - Fix bug on Dockerfile build error
- 1.0.5 - Created a script to be run on docker image to fix the user/host/image permitions nightmare
- 1.0.5 - Made the configuration simpler
- 1.0.4 - Added CORS and exposed seetins of allowed CORS
- 1.0.3 - Fix bug with permissions and path calculation when running on the docker
- 1.0.2 - Changed from API_TOKENS environment variable to API_TOKENS_PATH for security and flexibility
- 1.0.1 - RESTful API endpoints
- 1.0.1 - WebSocket real-time updates
- 1.0.1 - Rate limiting
- 1.0.1 - Comprehensive logging
- 1.0.1 - Full test coverage
- 1.0.1 - Docker