This project is a simple Cloudflare Worker that provides a JSON API endpoint.
graph TD;
A[Client] --> B(Cloudflare Worker);
B --> C{API Endpoint};
C --> D[JSON Response];
To develop and test the Cloudflare Worker locally, follow these steps:
- Clone the repository:
git clone https://github.com/your-username/cloudflare-worker.git cd cloudflare-worker - Install dependencies:
npm install
- Run the development server:
The development server will be available at
npm run dev
http://localhost:8787.
The v1 API provides several utility endpoints:
GET, POST, PUT, PATCH /v1/api/echo: Echoes the request method, headers, and body.GET /v1/api/time: Returns the current time in a specified timezone (defaults to UTC).- Query Parameter:
timezone(e.g.,America/New_York)
- Query Parameter:
GET /v1/api/headers: Returns the request headers.GET /v1/api/ip: Returns the client's IP address and geo-location information.
- Method:
GET - Description: Returns a JSON object with a welcome message, environment, and timestamp.
- Example Response:
{ "message": "Hello from Cloudflare Worker!", "environment": "development", "timestamp": "2024-05-15T12:00:00.000Z" }
You can test the endpoint using curl:
curl http://localhost:8787/api/helloThis project implements several security best practices:
- Rate Limiting: A simple in-memory rate limiter is in place to prevent abuse.
- Input Validation: All API inputs are validated using Zod to prevent common vulnerabilities.
- Security Headers: Responses include security headers like
X-Content-Type-Options,X-Frame-Options, andContent-Security-Policyto protect against attacks like XSS and clickjacking. - Request Size Limits: The maximum request size is limited to 1MB to prevent denial-of-service attacks.
The worker is configured with the following observability tools:
- Sentry: For error tracking. Set the
SENTRY_DSNenvironment variable to enable. - OpenTelemetry: For distributed tracing. Set the
OTLP_ENDPOINTenvironment variable to enable.
This project uses GitHub Actions for CI/CD. The .github/workflows/deploy.yml workflow automatically deploys the worker to Cloudflare when changes are pushed to the Scarmonit branch.
To deploy the Cloudflare Worker, use the following command:
npm run deployThe following environment variables are used in this project:
| Variable | Description | Default |
|---|---|---|
ENVIRONMENT |
The environment of the worker. | production |