URL Shortener API in JavaScript: Node.js and Fetch Integration
Integrate the URLW URL shortener API in JavaScript or Node.js. Complete fetch-based examples, error handling, and patterns for React, Express, and serverless environments.
Whether you are building a Node.js backend, a serverless function, or a browser-based tool, the URLW API integrates seamlessly with modern JavaScript. The API uses standard REST conventions with JSON payloads, making it a natural fit for the fetch API available natively in Node.js 18+ and all modern browsers.
Setup and Authentication
Store your URLW API token in an environment variable. Never include it in client-side JavaScript that is served to browsers — API calls should always be proxied through your backend.
# .env (Node.js / dotenv)
URLW_API_TOKEN=your_api_token_here
In Node.js, load it with process.env.URLW_API_TOKEN. In serverless environments like Vercel or AWS Lambda, configure it as a secret environment variable in your deployment settings.
A Reusable API Client
// urlw.js
const URLW_BASE = 'https://urlw.fr/api/v1';
class UrlwClient {
constructor(token) {
this.token = token;
this.headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
};
}
async #request(method, endpoint, body = null) {
const url = `${URLW_BASE}${endpoint}`;
const options = {
method,
headers: this.headers,
};
if (body !== null) {
options.body = JSON.stringify(body);
}
const response = await fetch(url, options);
if (!response.ok) {
const error = await response.json().catch(() => ({}));
const code = error.code ?? 'api_error';
const message = error.message ?? `HTTP ${response.status}`;
throw new Error(`URLW [${code}]: ${message}`);
}
if (response.status === 204) return null;
return response.json();
}
async createLink(url, { slug, domain } = {}) {
const payload = { url };
if (slug) payload.slug = slug;
if (domain) payload.domain = domain;
return this.#request('POST', '/links', payload);
}
async getLink(id) {
return this.#request('GET', `/links/${id}`);
}
async getLinkStats(id) {
return this.#request('GET', `/links/${id}/stats`);
}
async listLinks({ page = 1, perPage = 50 } = {}) {
return this.#request('GET', `/links?page=${page}&per_page=${perPage}`);
}
async deleteLink(id) {
return this.#request('DELETE', `/links/${id}`);
}
}
export default UrlwClient;
Practical Usage Examples
// app.js (Node.js / ESM)
import UrlwClient from './urlw.js';
const client = new UrlwClient(process.env.URLW_API_TOKEN);
// Create a short link
async function shortenForNewsletter(targetUrl, campaignSlug) {
try {
const link = await client.createLink(targetUrl, { slug: campaignSlug });
console.log('Short URL:', link.short_url);
return link.short_url;
} catch (err) {
console.error('Failed to shorten URL:', err.message);
throw err;
}
}
// Retrieve click statistics
async function getStats(linkId) {
const stats = await client.getLinkStats(linkId);
console.log(`Total clicks: ${stats.total_clicks}`);
console.log(`Top country: ${stats.countries?.[0]?.name}`);
return stats;
}
// Example: shorten and immediately check stats
const link = await shortenForNewsletter(
'https://mysite.com/article/new-feature',
'newsletter-june-feature'
);
Express.js Proxy Endpoint
If your frontend needs to shorten URLs, never expose your API token in browser code. Instead, create a server-side proxy:
// routes/shorten.js (Express)
import express from 'express';
import UrlwClient from '../lib/urlw.js';
const router = express.Router();
const urlw = new UrlwClient(process.env.URLW_API_TOKEN);
router.post('/shorten', async (req, res) => {
const { url, slug } = req.body;
if (!url) {
return res.status(400).json({ error: 'url is required' });
}
try {
const link = await urlw.createLink(url, { slug });
res.json({ shortUrl: link.short_url, id: link.id });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
export default router;
Serverless Function Example (Vercel)
// api/shorten.js (Vercel serverless function)
import UrlwClient from '../lib/urlw.js';
const client = new UrlwClient(process.env.URLW_API_TOKEN);
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { url, slug } = req.body;
const link = await client.createLink(url, { slug });
res.status(201).json({ shortUrl: link.short_url });
} catch (err) {
res.status(500).json({ error: err.message });
}
}
Next Steps
The complete API reference with all parameters, response schemas, and webhook documentation is at /en/docs/api. Create your account at /en/register and choose your plan at /en/#pricing.
Try URLW for free
50 short links, REST API included, no credit card required.