### Build and Run Node.js Example
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Commands to build the CounterAPI library and run the Node.js example. This example demonstrates ESM imports and error handling in a server-side context.
```bash
# Build the library first
npm run build
# Run the example
cd examples/node
node index.js
```
--------------------------------
### Serve Browser Example with http-server
Source: https://github.com/counterapi/counter.js/blob/main/examples/browser/README.md
Alternatively, use Node.js's http-server package to serve the CounterAPI browser example on port 8000. Ensure http-server is installed globally.
```bash
cd examples/browser
http-server -p 8000
```
--------------------------------
### Build and Serve Browser Example
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Commands to build the CounterAPI library and serve the browser example using Python's http.server. Ensure you have built the library before serving the example.
```bash
# Build the library first
npm run build
# Serve the example using a web server
cd examples/browser
python -m http.server 8000
# Then open http://localhost:8000 in your browser
```
--------------------------------
### Serve Browser Example with Python HTTP Server
Source: https://github.com/counterapi/counter.js/blob/main/examples/browser/README.md
Navigate to the example directory and use Python's built-in HTTP server to serve the CounterAPI browser example on port 8000.
```bash
cd examples/browser
python -m http.server 8000
```
--------------------------------
### Run Node.js Example
Source: https://github.com/counterapi/counter.js/blob/main/examples/node/README.md
Execute this command to run the Node.js example that fetches a counter from CounterAPI using the v1 API.
```bash
node index.js
```
--------------------------------
### Install CounterAPI npm package
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Install the CounterAPI JavaScript client using npm. This is the recommended method for Node.js and modern frontend projects.
```bash
npm install counterapi
```
--------------------------------
### CounterAPI JavaScript Client Initialization and Usage
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Initializes the CounterAPI client with a workspace and demonstrates how to use its methods (up, down, get, reset) to interact with a named counter. Includes event listeners for buttons and UI updates.
```javascript
// Initialize CounterAPI client
const counter = new Counter({
workspace: 'test' // Replace with your workspace
});
// Counter name
const counterName = 'demo-counter';
// DOM elements
const upCountElement = document.getElementById('up-count');
const downCountElement = document.getElementById('down-count');
const responseElement = document.getElementById('response');
// Button event listeners
document.getElementById('btn-up').addEventListener('click', async () => {
try {
const result = await counter.up(counterName);
updateUI(result);
} catch (error) {
handleError(error);
}
});
document.getElementById('btn-down').addEventListener('click', async () => {
try {
const result = await counter.down(counterName);
updateUI(result);
} catch (error) {
handleError(error);
}
});
document.getElementById('btn-get').addEventListener('click', async () => {
try {
const result = await counter.get(counterName);
updateUI(result);
} catch (error) {
handleError(error);
}
});
document.getElementById('btn-reset').addEventListener('click', async () => {
try {
const result = await counter.reset(counterName);
updateUI(result);
} catch (error) {
handleError(error);
}
});
// Update UI with response data
function updateUI(result) {
// Display full response
responseElement.textContent = JSON.stringify(result, null, 2);
// Extract data
const data = result.data || result;
// Update counter displays
if (data) {
if (data.up_count !== undefined) {
upCountElement.textContent = data.up_count;
}
if (data.down_count !== undefined) {
downCountElement.textContent = data.down_count;
}
}
}
// Handle errors
function handleError(error) {
console.error('Error:', error);
responseElement.textContent = 'Error: ' + (error.message || JSON.stringify(error));
}
// Get initial counter value
counter.get(counterName).then(updateUI).catch(handleError);
```
--------------------------------
### HTML Structure for CounterAPI Example
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Provides the HTML boilerplate, including meta tags, styling, and DOM elements for displaying counter values and interacting with the CounterAPI. It also includes the script tag for loading the CounterAPI CDN.
```html
CounterAPI CDN Example
CounterAPI Example
Up Count
-
Down Count
-
```
--------------------------------
### Complete Browser Example with CounterAPI
Source: https://context7.com/counterapi/counter.js/llms.txt
This HTML and JavaScript code demonstrates how to use CounterAPI in a browser. It includes buttons to increment, decrement, and reset a counter, and displays the current count and API responses. Ensure the CounterAPI library is included via CDN.
```html
CounterAPI Example
Page Views: -
```
--------------------------------
### Get Counter Value
Source: https://context7.com/counterapi/counter.js/llms.txt
Retrieve the current value of a counter without modifying it. This function demonstrates how to initialize a client and use the `get` method to fetch counter data. It includes basic error handling for the asynchronous operation.
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({ workspace: 'my-workspace' });
async function getCounterValue() {
try {
const result = await counter.get('page-views');
console.log('Counter data:', result);
// Response structure:
// {
// code: "200",
// data: {
// name: "page-views",
// up_count: 42,
// down_count: 5,
// workspace_slug: "my-workspace",
// created_at: "2025-06-17T11:33:23Z",
// updated_at: "2025-06-17T11:33:23Z"
// }
// }
} catch (error) {
console.error('Error:', error.message);
}
}
getCounterValue();
```
--------------------------------
### Get counter value using API
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Retrieve the current value of a specified counter. Requires an initialized Counter client instance.
```javascript
// Get the current value of a counter
const counter = await counterClient.get('page-views');
console.log(`Current count: ${counter.value}`);
```
--------------------------------
### Get counter statistics (V2 API only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Retrieve detailed statistics for a counter, including counts, temporal breakdowns, and activity by hour and day. This method is only available for the v2 API.
```javascript
// Get statistics for a counter
const result = await counterV2.stats('page-views');
console.log(`Up count: ${result.data.up_count}`);
console.log(`Down count: ${result.data.down_count}`);
console.log(`Today's up count: ${result.data.stats.today.up}`);
console.log(`This week's down count: ${result.data.stats.this_week.down}`);
console.log(`Most active hour: ${getMostActiveHour(result.data.stats.temporal.hours)}`);
```
--------------------------------
### Counter API Application Initialization
Source: https://github.com/counterapi/counter.js/blob/main/examples/browser/index.html
Initializes the Counter API application by getting DOM elements, creating a Counter instance, and setting up event listeners for various counter operations. Handles workspace changes and updates the UI accordingly.
```javascript
function initApp() {
if (typeof Counter === 'undefined') {
console.error('CounterAPI library not loaded');
document.getElementById('response-area').textContent = 'Error: CounterAPI library not loaded';
return;
}
// Get DOM elements
const workspaceInput = document.getElementById('workspace');
const counterInput = document.getElementById('counter');
const upCountElement = document.getElementById('up-count');
const downCountElement = document.getElementById('down-count');
const responseArea = document.getElementById('response-area');
const upButton = document.getElementById('btn-up');
const downButton = document.getElementById('btn-down');
const getButton = document.getElementById('btn-get');
const resetButton = document.getElementById('btn-reset');
const statsButton = document.getElementById('btn-stats');
// Create a Counter instance
let counter = new Counter({ workspace: workspaceInput.value });
// Update counter instance when workspace changes
workspaceInput.addEventListener('change', () => {
counter = new Counter({ workspace: workspaceInput.value });
updateCounter();
});
// Button event listeners
upButton.addEventListener('click', incrementCounter);
downButton.addEventListener('click', decrementCounter);
getButton.addEventListener('click', updateCounter);
resetButton.addEventListener('click', resetCounter);
statsButton.addEventListener('click', getStats);
// Get initial counter value
updateCounter();
// Increment counter
async function incrementCounter() {
setLoading(true);
try {
const result = await counter.up(counterInput.value);
updateUI(result);
} catch (error) {
handleError(error);
}
setLoading(false);
}
// Decrement counter
async function decrementCounter() {
setLoading(true);
try {
const result = await counter.down(counterInput.value);
updateUI(result);
} catch (error) {
handleError(error);
}
setLoading(false);
}
// Update counter display
async function updateCounter() {
setLoading(true);
try {
const result = await counter.get(counterInput.value);
updateUI(result);
} catch (error) {
handleError(error);
}
setLoading(false);
}
// Reset counter
async function resetCounter() {
setLoading(true);
try {
const result = await counter.reset(counterInput.value);
updateUI(result);
} catch (error) {
handleError(error);
}
setLoading(false);
}
// Get counter stats
async function getStats() {
setLoading(true);
try {
const result = await counter.stats(counterInput.value);
updateUI(result);
} catch (error) {
handleError(error);
}
setLoading(false);
}
// Update UI with response
function updateUI(result) {
// Format the JSON with 2 spaces of indentation
responseArea.textContent = JSON.stringify(result, null, 2);
// Extract data from different response formats
let data = result;
// Handle nested data structure if present
if (result && result.data) {
data = result.data;
}
// Update counter value displays
if (data) {
// For v2 API responses with up_count and down_count
if (data.up_count !== undefined) {
upCountElement.textContent = data.up_count;
}
if (data.down_count !== undefined) {
downCountElement.textContent = data.down_count;
}
// For v1 API responses or other formats
if (data.up_count === undefined && data.down_count === undefined) {
if (data.count !== undefined) {
upCountElement.textContent = data.count;
downCountElement.textContent = '0';
} else if (data.value !== undefined) {
upCountElement.textContent = data.value;
downCountElement.textContent = '0';
}
}
}
}
// Handle errors
function handleError(error) {
console.error('CounterAPI error:', error);
responseArea.textContent = 'Error: ' + (error.message || JSON.stringify(error));
upCountElement.textContent = '?';
downCountElement.textContent = '?';
}
// Set loading state
function setLoading(isLoading) {
const buttons = [upButton, downButton, getButton, resetButton, statsButton];
if (isLoading) {
buttons.forEach(btn => btn.disabled = true);
responseArea.textContent = 'Loading...';
} else {
buttons.forEach(btn => btn.disabled = false);
}
}
}
```
--------------------------------
### Get Counter Stats (V2 API Only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Retrieves detailed statistics for a counter, including daily, weekly, and hourly breakdowns. This method is only available for the v2 API.
```APIDOC
## GET /counter/{name}/stats
### Description
Get statistics for a counter. This method is only available for the v2 API.
### Method
GET
### Endpoint
`/counter/{name}/stats`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name or slug of the counter.
### Request Example
```js
// Assuming counterV2 is an initialized Counter instance for v2 API
const result = await counterV2.stats('page-views');
console.log(`Up count: ${result.data.up_count}`);
console.log(`Down count: ${result.data.down_count}`);
console.log(`Today's up count: ${result.data.stats.today.up}`);
console.log(`This week's down count: ${result.data.stats.this_week.down}`);
```
### Response
#### Success Response (200)
- **data.up_count** (number) - Total increments.
- **data.down_count** (number) - Total decrements.
- **data.stats.today** (object) - Statistics for the current day.
- **data.stats.this_week** (object) - Statistics for the current week.
- **data.stats.temporal.hours** (object) - Hourly breakdown of activity.
- **data.stats.temporal.weekdays** (object) - Day of week breakdown of activity.
- **data.stats.temporal.quarters** (object) - Quarterly breakdown of activity.
#### Response Example
```json
{
"code": "200",
"data": {
"id": 1,
"counter_id": 1,
"up_count": 6,
"down_count": 4,
"stats": {
"today": {
"up": 6,
"down": 4
},
"this_week": {
"up": 6,
"down": 4
},
"temporal": {
"hours": {
"07": { "up": 6, "down": 4 },
"08": { "up": 0, "down": 0 }
},
"weekdays": {
"monday": { "up": 0, "down": 0 },
"tuesday": { "up": 0, "down": 0 },
"wednesday": { "up": 6, "down": 4 }
},
"quarters": {
"q1": { "up": 0, "down": 0 },
"q2": { "up": 6, "down": 4 },
"q3": { "up": 0, "down": 0 },
"q4": { "up": 0, "down": 0 }
}
}
},
"created_at": "2025-06-17T11:33:23Z",
"updated_at": "2025-06-18T07:44:11Z"
},
"message": "Counter stats retrieved successfully"
}
```
```
--------------------------------
### Get Counter Statistics (v2 API Only)
Source: https://context7.com/counterapi/counter.js/llms.txt
Retrieves detailed statistics for a counter including temporal breakdowns. This method is only available in the v2 API.
```APIDOC
## Get Counter Statistics (v2 API Only)
### Description
Retrieve detailed statistics for a counter including temporal breakdowns. This method is only available in the v2 API.
### Method
GET (implied by `stats` operation, though not explicitly stated in JS example)
### Endpoint
`/v2/{workspace}/{counter_name}/stats` (inferred)
### Parameters
#### Path Parameters
- **workspace** (string) - Required - The workspace name.
- **counter_name** (string) - Required - The name of the counter.
### Request Example
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({ workspace: 'my-workspace' });
async function getCounterStats() {
try {
const result = await counter.stats('page-views');
console.log(`Up count: ${result.data.up_count}`);
console.log(`Down count: ${result.data.down_count}`);
console.log(`Today's up count: ${result.data.stats.today.up}`);
console.log(`This week's down count: ${result.data.stats.this_week.down}`);
} catch (error) {
console.error('Error:', error.message);
}
}
getCounterStats();
```
### Response
#### Success Response (200)
- **data** (object) - Contains the counter statistics.
- **id** (integer) - The counter ID.
- **counter_id** (integer) - The counter's unique identifier.
- **up_count** (integer) - Total up count.
- **down_count** (integer) - Total down count.
- **stats** (object) - Temporal statistics.
- **today** (object) - Statistics for the current day.
- **up** (integer) - Up count for today.
- **down** (integer) - Down count for today.
- **this_week** (object) - Statistics for the current week.
- **up** (integer) - Up count for this week.
- **down** (integer) - Down count for this week.
- **temporal** (object) - Detailed temporal breakdowns.
- **hours** (object) - Breakdown by hour.
- **weekdays** (object) - Breakdown by weekday.
- **quarters** (object) - Breakdown by quarter.
- **created_at** (string) - Timestamp of counter creation.
- **updated_at** (string) - Timestamp of last update.
- **message** (string) - A message indicating success.
#### Response Example
```json
{
"code": "200",
"data": {
"id": 1,
"counter_id": 1,
"up_count": 6,
"down_count": 4,
"stats": {
"today": { "up": 6, "down": 4 },
"this_week": { "up": 6, "down": 4 },
"temporal": {
"hours": { "07": { "up": 6, "down": 4 } },
"weekdays": { "monday": { "up": 0, "down": 0 }, "wednesday": { "up": 6, "down": 4 } },
"quarters": { "q1": { "up": 0, "down": 0 }, "q2": { "up": 6, "down": 4 } }
}
},
"created_at": "2025-06-17T11:33:23Z",
"updated_at": "2025-06-18T07:44:11Z"
},
"message": "Counter stats retrieved successfully"
}
```
```
--------------------------------
### Increment Counter Value
Source: https://context7.com/counterapi/counter.js/llms.txt
Increment a counter's value by 1 using the `up()` method. This example shows how to call the method and log the updated count from the response. It also includes error handling for the asynchronous operation.
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({ workspace: 'my-workspace' });
async function incrementCounter() {
try {
const result = await counter.up('page-views');
console.log(`New count after increment: ${result.data.up_count}`);
console.log(`Up count: ${result.data.up_count}, Down count: ${result.data.down_count}`);
// Response:
// {
// code: "200",
// data: {
// name: "page-views",
// up_count: 43,
// down_count: 5,
// workspace_slug: "my-workspace",
// updated_at: "2025-06-17T12:00:00Z"
// }
// }
} catch (error) {
console.error('Error:', error.message);
}
}
incrementCounter();
```
--------------------------------
### Get Counter Value
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Retrieves the current value of a specified counter.
```APIDOC
## GET /counter/{name}
### Description
Get the current value of a counter.
### Method
GET
### Endpoint
`/counter/{name}`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name or slug of the counter.
### Request Example
```js
// Assuming counterClient is an initialized Counter instance
const counter = await counterClient.get('page-views');
console.log(`Current count: ${counter.value}`);
```
### Response
#### Success Response (200)
- **value** (number) - The current value of the counter.
#### Response Example
```json
{
"code": "200",
"data": {
"created_at": "2025-06-17T11:33:23Z",
"description": "",
"down_count": 4,
"id": 1,
"name": "page-views",
"slug": "page-views",
"team_id": 4,
"up_count": 4,
"updated_at": "2025-06-17T11:33:23Z",
"user_id": 7,
"workspace_id": 1,
"workspace_slug": "my-workspace"
}
}
```
```
--------------------------------
### Decrement Counter Value
Source: https://context7.com/counterapi/counter.js/llms.txt
Decrement a counter's value by 1 using the `down()` method. This example demonstrates calling the method and logging the updated counts. Error handling for the asynchronous operation is included.
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({ workspace: 'my-workspace' });
async function decrementCounter() {
try {
const result = await counter.down('page-views');
console.log(`New count after decrement: ${result.data.up_count - result.data.down_count}`);
console.log(`Up count: ${result.data.up_count}, Down count: ${result.data.down_count}`);
// Response:
// {
// code: "200",
// data: {
// name: "page-views",
// up_count: 43,
// down_count: 6,
// workspace_slug: "my-workspace",
// updated_at: "2025-06-17T12:01:00Z"
// }
// }
} catch (error) {
console.error('Error:', error.message);
}
}
decrementCounter();
```
--------------------------------
### Build CounterAPI Library
Source: https://github.com/counterapi/counter.js/blob/main/examples/node/README.md
Run this command from the project root to build the CounterAPI library.
```bash
npm run build
```
--------------------------------
### CounterAPI Client Initialization
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Demonstrates how to create instances of the CounterAPI client for both v1 and v2 APIs, including configuration options.
```APIDOC
## CounterAPI Client Initialization
### Description
Initialize the CounterAPI client with specific configurations for version, namespace, workspace, and other options.
### Creating a Client
```js
// For v1 API
const counterV1 = new Counter({
version: 'v1', // Use v1 API
namespace: 'my-app', // Your namespace
debug: false, // Optional: Enable debug logging
timeout: 5000, // Optional: Request timeout in ms (default: 10000)
});
// For v2 API (default)
const counterV2 = new Counter({
workspace: 'my-workspace', // Your workspace name
debug: false, // Optional: Enable debug logging
timeout: 5000, // Optional: Request timeout in ms (default: 10000)
accessToken: 'your-token' // Optional: Authentication token for API requests
});
```
```
--------------------------------
### Initialize Counter Client (v2 API)
Source: https://context7.com/counterapi/counter.js/llms.txt
Initialize a Counter client for the v2 API, which is the default and recommended version. Basic initialization requires a workspace identifier. Full configuration allows for enabling debug logging, setting a custom request timeout, and providing an access token for authentication.
```javascript
import { Counter } from 'counterapi';
// Basic v2 client initialization
const counter = new Counter({
workspace: 'my-workspace'
});
```
```javascript
import { Counter } from 'counterapi';
// Full configuration with all options
const counterWithOptions = new Counter({
workspace: 'my-workspace',
debug: true, // Enable debug logging
timeout: 5000, // Request timeout in ms (default: 10000)
accessToken: 'your-token' // Optional authentication token
});
```
--------------------------------
### Include CounterAPI via CDN (Minified)
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Use this script tag to include the minified CounterAPI library for production. Initialize the Counter with your workspace ID and then use its methods like 'up' to increment counters.
```html
```
--------------------------------
### Create CounterAPI client instance for v2 API
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Instantiate the Counter client for the v2 API (default). Configure with workspace, debug mode, timeout, and an optional access token.
```javascript
// For v2 API (default)
const counterV2 = new Counter({
workspace: 'my-workspace', // Your workspace name
debug: false, // Optional: Enable debug logging
timeout: 5000, // Optional: Request timeout in ms (default: 10000)
accessToken: 'your-token' // Optional: Authentication token for API requests
});
```
--------------------------------
### Create CounterAPI client instance for v1 API
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Instantiate the Counter client specifically for the v1 API. Configure with namespace, debug mode, and request timeout.
```javascript
// For v1 API
const counterV1 = new Counter({
version: 'v1', // Use v1 API
namespace: 'my-app', // Your namespace
debug: false, // Optional: Enable debug logging
timeout: 5000, // Optional: Request timeout in ms (default: 10000)
});
```
--------------------------------
### Include CounterAPI via CDN (Specific Version)
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Include a specific version of the minified CounterAPI library for production environments to ensure stability and prevent unexpected updates.
```html
```
--------------------------------
### Initialize Counter API in Browser
Source: https://github.com/counterapi/counter.js/blob/main/examples/browser/index.html
Load the Counter API library asynchronously and initialize the application upon successful loading. Ensure the library is correctly referenced, preferably from a CDN for production.
```javascript
const script = document.createElement('script');
script.async = true;
// For production use the CDN
script.src = 'https://cdn.jsdelivr.net/npm/counterapi/dist/counter.browser.min.js';
// When script is loaded, initialize the application
script.onload = initApp;
// Append the script to the document
document.head.appendChild(script);
```
--------------------------------
### Initialize Counter API with Module Pattern
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Use this pattern to encapsulate the Counter API initialization within a self-executing function, preventing global scope pollution. Ensure the script is loaded before this block.
```html
```
--------------------------------
### Include CounterAPI via CDN (Unminified)
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Include the unminified version of the CounterAPI library for development purposes. This version is not optimized for size and may be slower.
```html
```
--------------------------------
### Browser Usage via CDN
Source: https://context7.com/counterapi/counter.js/llms.txt
Load the CounterAPI library directly in the browser using a CDN. This method avoids the need for build tools. You can use the latest minified version for production or a specific version for stability. After loading, the Counter class is available as a global variable.
```html
```
--------------------------------
### Create Hourly Chart from Stats
Source: https://github.com/counterapi/counter.js/blob/main/README.md
JavaScript function to create a chart from hourly statistics data provided by CounterAPI. Requires a charting library for rendering.
```javascript
// Example: Creating a simple chart from hourly stats
function createHourlyChart(stats) {
const hours = stats.data.stats.temporal.hours;
const labels = Object.keys(hours).sort();
const upData = labels.map(hour => hours[hour].up);
const downData = labels.map(hour => hours[hour].down);
// Use your preferred charting library
renderChart({
labels,
datasets: [
{ label: 'Up', data: upData },
{ label: 'Down', data: downData }
]
});
}
// Example usage
const stats = await counter.stats('my-counter');
createHourlyChart(stats);
```
--------------------------------
### Initialize Counter Client (v1 API)
Source: https://context7.com/counterapi/counter.js/llms.txt
Initialize a Counter client for the v1 API using a namespace identifier. This is useful for maintaining compatibility with older applications. Configuration options include specifying the version, namespace, debug mode, and request timeout.
```javascript
import { Counter } from 'counterapi';
const counterV1 = new Counter({
version: 'v1',
namespace: 'my-app',
debug: false,
timeout: 5000
});
```
--------------------------------
### Import Counter module using ES Modules
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Import the Counter class from the 'counterapi' package using ES Module syntax. This is the recommended import method.
```javascript
import { Counter } from 'counterapi';
```
--------------------------------
### Import Counter module using CommonJS
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Import the Counter class from the 'counterapi' package using CommonJS syntax. Suitable for Node.js environments that do not use ES Modules.
```javascript
const { Counter } = require('counterapi');
```
--------------------------------
### Include CounterAPI client in browser via CDN
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Include the CounterAPI JavaScript client in your HTML file using a CDN link. The Counter class will be available as a global variable.
```html
```
--------------------------------
### Error Handling
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Demonstrates how to handle errors that may occur during API requests using standard Promise error handling.
```APIDOC
## Error Handling
### Description
Use standard Promise error handling to catch and manage errors from API requests.
### Example
```js
try {
const counter = await counterClient.up('page-views');
} catch (error) {
console.error('Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
}
```
### Error Response Structure
Errors typically return an object with the following properties:
- **message** (string) - A human-readable error message.
- **status** (number) - The HTTP status code of the error response.
- **code** (string) - An internal error code for the specific error.
```
--------------------------------
### Load Counter API with Integrity Check
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Incorporate this script tag to load the Counter API with a Subresource Integrity (SRI) hash for enhanced security. Obtain the correct SRI hash from JSDelivr.
```html
```
--------------------------------
### Handle API errors with Promises
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Implement standard Promise error handling using a try-catch block to manage potential errors during API requests. Access error details like message, status, and code.
```javascript
try {
const counter = await counterClient.up('page-views');
} catch (error) {
console.error('Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
}
```
--------------------------------
### Load Specific Version of Counter API
Source: https://github.com/counterapi/counter.js/blob/main/CDN.md
Include this script tag to load a particular version of the Counter API. This is useful for ensuring compatibility or testing specific releases.
```html
```
--------------------------------
### Debug Mode
Source: https://context7.com/counterapi/counter.js/llms.txt
Enables debug mode to log all HTTP requests and responses for troubleshooting.
```APIDOC
## Debug Mode
### Description
Enable debug mode to log all HTTP requests and responses for troubleshooting.
### Method
N/A (This is a configuration option)
### Endpoint
N/A
### Parameters
When initializing the `Counter` client:
- **debug** (boolean) - Required - Set to `true` to enable debug logging.
### Request Example
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({
workspace: 'my-workspace',
debug: true // Enable debug logging
});
// All API calls will now log request/response details
counter.up('page-views').then(result => {
console.log(result);
});
```
### Console Output Example (when debug is true)
```
[CounterAPI] Request: { method: 'GET', url: '/my-workspace/page-views/up', ... }
[CounterAPI] Response: { status: 200, data: { ... } }
```
```
--------------------------------
### Error Handling in Counter API
Source: https://context7.com/counterapi/counter.js/llms.txt
Demonstrates how to handle API errors using standard Promise error handling. The error object provides detailed information including message, status, code, and specific details.
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({ workspace: 'my-workspace' });
async function safeCounterOperation() {
try {
const result = await counter.up('page-views');
console.log('Success:', result);
} catch (error) {
// Error object structure:
// {
// message: "Request failed",
// status: 404,
// code: "NOT_FOUND",
// details: { ... }
// }
console.error('Error message:', error.message);
console.error('HTTP status:', error.status);
console.error('Error code:', error.code);
console.error('Details:', error.details);
}
}
safeCounterOperation();
```
--------------------------------
### Set Counter Value (V1 API Only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Sets a counter to a specific value. This method is only available for the v1 API.
```APIDOC
## PUT /counter/{name}
### Description
Set a counter to a specific value. This method is only available for the v1 API.
### Method
PUT
### Endpoint
`/counter/{name}`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name or slug of the counter.
#### Request Body
- **value** (number) - Required - The value to set the counter to.
### Request Example
```js
// Assuming counterV1 is an initialized Counter instance for v1 API
const counter = await counterV1.set('page-views', 100);
console.log(`Counter set to: ${counter.value}`);
```
### Response
#### Success Response (200)
- **value** (number) - The new value of the counter.
#### Response Example
```json
{
"code": "200",
"data": {
"created_at": "2025-06-17T11:33:23Z",
"description": "",
"down_count": 4,
"id": 1,
"name": "page-views",
"slug": "page-views",
"team_id": 4,
"up_count": 4,
"updated_at": "2025-06-17T11:33:23Z",
"user_id": 7,
"workspace_id": 1,
"workspace_slug": "my-workspace"
}
}
```
```
--------------------------------
### Set counter value (V1 API only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Set a counter to a specific value. This method is only available for the v1 API.
```javascript
// Set a counter to a specific value
const counter = await counterV1.set('page-views', 100);
console.log(`Counter set to: ${counter.value}`);
```
--------------------------------
### Standard Counter Response Structure
Source: https://github.com/counterapi/counter.js/blob/main/README.md
The typical structure of a response object for basic counter operations, including creation timestamp, counts, and identifiers.
```json
{
"code": "200",
"data": {
"created_at": "2025-06-17T11:33:23Z",
"description": "",
"down_count": 4,
"id": 1,
"name": "test",
"slug": "test",
"team_id": 4,
"up_count": 4,
"updated_at": "2025-06-17T11:33:23Z",
"user_id": 7,
"workspace_id": 1,
"workspace_slug": "test"
}
}
```
--------------------------------
### Enable Debug Mode in Counter API
Source: https://context7.com/counterapi/counter.js/llms.txt
Enables debug mode by setting the 'debug' option to true during Counter initialization. This logs all HTTP requests and responses for troubleshooting purposes.
```javascript
import { Counter } from 'counterapi';
const counter = new Counter({
workspace: 'my-workspace',
debug: true // Enable debug logging
});
// All API calls will now log request/response details
counter.up('page-views').then(result => {
// Console output:
// [CounterAPI] Request: { method: 'GET', url: '/my-workspace/page-views/up', ... }
// [CounterAPI] Response: { status: 200, data: { ... } }
console.log(result);
});
```
--------------------------------
### Reset Counter (V2 API Only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Resets a counter to 0. This method is only available for the v2 API.
```APIDOC
## POST /counter/{name}/reset
### Description
Reset a counter to 0. This method is only available for the v2 API.
### Method
POST
### Endpoint
`/counter/{name}/reset`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name or slug of the counter.
### Request Example
```js
// Assuming counterV2 is an initialized Counter instance for v2 API
const counter = await counterV2.reset('page-views');
console.log(`Counter reset to: ${counter.value}`);
```
### Response
#### Success Response (200)
- **value** (number) - The value of the counter after reset (should be 0).
#### Response Example
```json
{
"code": "200",
"data": {
"created_at": "2025-06-17T11:33:23Z",
"description": "",
"down_count": 4,
"id": 1,
"name": "page-views",
"slug": "page-views",
"team_id": 4,
"up_count": 4,
"updated_at": "2025-06-17T11:33:23Z",
"user_id": 7,
"workspace_id": 1,
"workspace_slug": "my-workspace"
}
}
```
```
--------------------------------
### Stats Response Structure (V2 API)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
The detailed structure of a response object returned by the `stats()` method for the v2 API, including comprehensive statistical breakdowns.
```json
{
"code": "200",
"data": {
"id": 1,
"counter_id": 1,
"up_count": 6,
"down_count": 4,
"stats": {
"today": {
"up": 6,
"down": 4
},
"this_week": {
"up": 6,
"down": 4
},
"temporal": {
"hours": {
// Hourly breakdown (00-23)
"07": { "up": 6, "down": 4 },
// ... other hours
},
"weekdays": {
// Day of week breakdown
"monday": { "up": 0, "down": 0 },
"tuesday": { "up": 0, "down": 0 },
"wednesday": { "up": 6, "down": 4 },
// ... other days
},
"quarters": {
// Quarterly breakdown
"q1": { "up": 0, "down": 0 },
"q2": { "up": 6, "down": 4 },
"q3": { "up": 0, "down": 0 },
"q4": { "up": 0, "down": 0 }
}
}
},
"created_at": "2025-06-17T11:33:23Z",
"updated_at": "2025-06-18T07:44:11Z"
},
"message": "Counter stats retrieved successfully"
}
```
--------------------------------
### Reset counter value (V2 API only)
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Reset a counter to 0. This method is only available for the v2 API.
```javascript
// Reset a counter to 0
const counter = await counterV2.reset('page-views');
console.log(`Counter reset to: ${counter.value}`);
```
--------------------------------
### Increment counter value using API
Source: https://github.com/counterapi/counter.js/blob/main/README.md
Increment the value of a specified counter by 1. Returns the updated counter object.
```javascript
// Increment a counter by 1
const counter = await counterClient.up('page-views');
console.log(`New count after increment: ${counter.value}`);
console.log(`Up count: ${counter.data.up_count}, Down count: ${counter.data.down_count}`);
```