@rezamirzapour/http
v1.0.2
Published
An enterprise-grade, isomorphic, type-safe HTTP client tailored for Next.js App Router, Server Actions, and Client Components.
Maintainers
Readme
@rezamirzapour/http 🚀
An enterprise-grade, isomorphic, type-safe HTTP client specifically engineered for Next.js (App Router, Server Components, Server Actions, Route Handlers, and Client Components).
📑 Table of Contents
- Why @rezamirzapour/http?
- Installation
- Quick Start
- Comprehensive Next.js Examples
- Core Features & Guides
- Logging & Sensitive Data Masking
- Comprehensive Error Handling
- API Reference
- License
💡 Why @rezamirzapour/http?
While native fetch and general-purpose libraries (Axios, Ky) are great, Next.js introduces unique paradigms:
- Caching & Revalidation: Next.js extends fetch with
next: { revalidate, tags }andcache: 'force-cache' | 'no-store'. Most libraries strip or ignore these headers. - Server vs Client Runtime Boundaries: Libraries that import Node.js modules (
fs,crypto,http) break Client Components and Edge Middleware. - Session & Cookie Forwarding: In Server Actions and RSC, backend requests often need to forward incoming user cookies and auth headers.
- Thundering Herd on 401: When multiple parallel requests receive 401, naive refresh token logic fires multiple duplicate refresh requests.
@rezamirzapour/http solves all of these out of the box with zero runtime dependencies.
📦 Installation
npm install @rezamirzapour/http @rezamirzapour/logger
# or
pnpm add @rezamirzapour/http @rezamirzapour/logger
# or
yarn add @rezamirzapour/http @rezamirzapour/logger🚀 Quick Start
1. Initialize Client
Create a centralized HTTP client instance in your project:
// lib/http.ts
import { createNextHttp } from '@rezamirzapour/http';
export const http = createNextHttp({
baseUrl: process.env.NEXT_PUBLIC_API_URL || 'https://api.example.com',
timeout: 10000, // 10 seconds
headers: {
'Accept': 'application/json',
},
});2. Make Requests
interface User {
id: number;
name: string;
email: string;
}
// GET
const user = await http.get<User>('/users/1');
// POST
const newUser = await http.post<User>('/users', {
name: 'Sarah Connor',
email: '[email protected]',
});
// PUT
const updated = await http.put<User>('/users/1', { name: 'Sarah J. Connor' });
// DELETE
await http.delete('/users/1');🧩 Comprehensive Next.js Examples
1. Server Components (RSC) with Data Cache & Tags
Take full advantage of Next.js App Router caching, Static Site Generation (SSG), and Incremental Static Regeneration (ISR):
// app/products/page.tsx
import { http } from '@/lib/http';
interface Product {
id: string;
title: string;
price: number;
}
export default async function ProductsPage() {
// Leverages Next.js Data Cache: cached for 1 hour with on-demand tag
const products = await http.get<Product[]>('/products', {
cache: 'force-cache',
next: {
revalidate: 3600, // ISR: revalidate every hour
tags: ['products-list'], // Can be invalidated with revalidateTag('products-list')
},
});
return (
<main className="p-8">
<h1 className="text-2xl font-bold">Products</h1>
<div className="grid grid-cols-3 gap-4 mt-4">
{products.map((p) => (
<div key={p.id} className="border p-4 rounded">
<h2>{p.title}</h2>
<p>${p.price}</p>
</div>
))}
</div>
</main>
);
}To purge the cache on-demand from a Server Action or Route Handler:
import { revalidateTag } from 'next/cache';
export async function onProductUpdated() {
'use server';
revalidateTag('products-list');
}2. Server Actions with Cookie Forwarding
When running Server Actions, forward the incoming user session cookie to your microservices or backend API seamlessly:
// app/actions/account.ts
'use server';
import { http } from '@/lib/http';
import { forwardServerCookies, forwardServerHeaders } from '@rezamirzapour/http/server';
export async function updateProfile(formData: FormData) {
const name = formData.get('name') as string;
const bio = formData.get('bio') as string;
// 1. Forward user session cookies
const cookies = await forwardServerCookies();
// 2. Forward tracing and client headers
const headers = await forwardServerHeaders(['x-request-id', 'user-agent']);
const response = await http.put('/api/user/profile', { name, bio }, {
headers: {
...headers,
Cookie: cookies,
},
});
return { success: true, data: response };
}3. Route Handlers (app/api/**/route.ts)
Proxy requests, forward headers, or fetch upstream services:
// app/api/orders/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { http } from '@/lib/http';
import { isHttpError } from '@rezamirzapour/http';
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const order = await http.get('/orders/:id', {
routeParams: { id: params.id },
headers: {
Authorization: request.headers.get('Authorization') || '',
},
// Never cache sensitive user order data
cache: 'no-store',
});
return NextResponse.json(order);
} catch (error) {
if (isHttpError(error)) {
return NextResponse.json(
{ error: error.message, details: error.data },
{ status: error.status }
);
}
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}4. Client Components with React Query / SWR
Works seamlessly in "use client" components:
// components/UserProfile.tsx
'use client';
import { useQuery } from '@tanstack/react-query';
import { http } from '@/lib/http';
interface Profile {
id: string;
username: string;
}
export function UserProfile({ userId }: { userId: string }) {
const { data, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: () =>
http.get<Profile>('/users/:id', {
routeParams: { id: userId },
}),
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading profile</div>;
return <div>Welcome, {data?.username}!</div>;
}5. Middleware & Edge Runtime
Because @rezamirzapour/http has zero Node.js filesystem dependencies, it runs reliably in Next.js Edge Middleware:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createNextHttp } from '@rezamirzapour/http';
const authApi = createNextHttp({
baseUrl: process.env.INTERNAL_AUTH_SERVICE_URL,
timeout: 3000,
});
export async function middleware(request: NextRequest) {
const token = request.cookies.get('session_token')?.value;
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
try {
const session = await authApi.post<{ valid: boolean }>('/sessions/verify', { token });
if (!session.valid) {
return NextResponse.redirect(new URL('/login', request.url));
}
} catch (err) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'],
};🛠️ Core Features & Guides
Type-Safe Route Parameters
Interpolate route variables automatically without string concatenation or template literal errors. Supports both Express (:param) and Next.js ([param]) conventions:
// 1. Express-style colon notation
await http.get('/users/:userId/posts/:postId', {
routeParams: {
userId: '102',
postId: 405,
},
});
// Resolves to: https://api.example.com/users/102/posts/405
// 2. Next.js bracket notation
await http.get('/organizations/[orgSlug]/projects/[projectSlug]', {
routeParams: {
orgSlug: 'acme-corp',
projectSlug: 'analytics-dashboard',
},
});
// Resolves to: https://api.example.com/organizations/acme-corp/projects/analytics-dashboardAdvanced Query Parameter Serialization
Query parameters support strings, numbers, booleans, arrays, and nested objects. Multiple array serialization strategies are supported:
// Repeat style (Default): ?tags=react&tags=next
await http.get('/search', {
params: {
q: 'nextjs http',
page: 1,
active: true,
tags: ['react', 'next'],
},
});
// Comma style: ?tags=react,next
await http.get('/search', {
params: { tags: ['react', 'next'] },
queryArrayFormat: 'comma',
});
// Bracket style: ?tags[]=react&tags[]=next
await http.get('/search', {
params: { tags: ['react', 'next'] },
queryArrayFormat: 'brackets',
});Automatic Retry with Exponential Backoff
Handle network hiccups, rate-limiting (HTTP 429), and temporary server downtime (HTTP 500, 502, 503, 504) automatically:
export const resilientHttp = createNextHttp({
baseUrl: 'https://api.example.com',
retry: {
retries: 3, // Retry up to 3 times
retryDelay: 1000, // Start with 1000ms delay
maxRetryDelay: 10000, // Maximum delay 10s
backoffFactor: 2, // 1s -> 2s -> 4s (+ jitter)
retryOnStatus: [408, 429, 500, 502, 503, 504],
onRetry: (attempt, error, config) => {
console.warn(`[Retry #${attempt}] for ${config.url}: ${error.message}`);
},
},
});[!TIP] If the backend returns a
Retry-Afterheader (e.g. on 429 Too Many Requests), the retry engine will automatically honor the server-requested wait duration!
JWT Auth & 401 Refresh Mutex Queue
Solve the notorious "Thundering Herd" problem. When an access token expires and multiple parallel requests fail with 401 simultaneously, the AuthManager executes the refresh token routine only once and queues other requests to resolve with the new token:
import { createNextHttp, createAuthManager } from '@rezamirzapour/http';
let accessToken: string | null = 'current-jwt-token';
const authManager = createAuthManager({
// Retrieve token dynamically
getToken: () => accessToken,
// Called on 401 - synchronized with a concurrency lock (mutex)
refreshToken: async () => {
const res = await fetch('https://api.example.com/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: getStoredRefreshToken() }),
});
if (!res.ok) throw new Error('Refresh failed');
const data = await res.json();
accessToken = data.accessToken;
return accessToken;
},
onAuthFailure: () => {
// Redirect user to login page if refresh fails
window.location.href = '/login';
},
});
export const http = createNextHttp({
baseUrl: 'https://api.example.com',
before: [authManager.getBeforeHook()],
});Request Lifecycle Hooks
Attach hooks to inspect or modify requests before execution, record response metrics, or handle errors centrally:
const http = createNextHttp({
baseUrl: 'https://api.example.com',
before: [
(ctx) => {
console.log(`🚀 [${ctx.method}] ${ctx.url} started`);
},
],
after: [
(ctx) => {
console.log(`✅ [${ctx.status}] ${ctx.url} finished in ${ctx.durationMs}ms`);
},
],
error: [
(ctx) => {
console.error(`❌ Request to ${ctx.url} failed:`, ctx.error);
},
],
});Client Inheritance (extend)
Create scoped sub-clients that inherit base configurations, headers, and hooks:
const baseApi = createNextHttp({
baseUrl: 'https://api.example.com',
headers: {
'X-App-Version': '2.0.0',
},
});
// Dedicated billing client
export const billingApi = baseApi.extend({
baseUrl: 'https://api.example.com/v2/billing',
headers: {
'X-Service': 'billing',
},
});
// Dedicated analytics client with different timeout
export const analyticsApi = baseApi.extend({
baseUrl: 'https://analytics.example.com',
timeout: 5000,
});Timeout & Cancellation
Configure timeouts globally or per-request using standard milliseconds:
// 1. Global client timeout
const http = createNextHttp({ timeout: 5000 });
// 2. Per-request timeout override
await http.get('/heavy-export', { timeout: 60000 });
// 3. Manual cancellation via AbortSignal
const controller = new AbortController();
const promise = http.get('/data', { signal: controller.signal });
// Cancel request
controller.abort();🔒 Logging & Sensitive Data Masking
By default, @rezamirzapour/http integrates seamlessly with @rezamirzapour/logger to automatically mask sensitive headers and payloads in logs:
import { httpService } from '@rezamirzapour/http';
// Automatically masks tokens, cookies, and passwords in output!
// Example log: [NEXT-KIT] GET /api/user [200] (45ms) { headers: { authorization: 'Bearer 1234******5678' } }🚨 Comprehensive Error Handling
@rezamirzapour/http provides rich error classes with convenient property getters:
import { http, isHttpError, isTimeoutError, isNetworkError } from '@rezamirzapour/http';
try {
const result = await http.get('/users/100');
} catch (err) {
if (isHttpError(err)) {
console.error('HTTP Status:', err.status); // e.g. 404
console.error('Status Text:', err.statusText);
console.error('Response Body:', err.data); // parsed JSON or text payload
console.error('Request URL:', err.url);
if (err.isUnauthorized) {
// 401 Unauthorized
} else if (err.isForbidden) {
// 403 Forbidden
} else if (err.isNotFound) {
// 404 Not Found
} else if (err.isServerError) {
// 5xx Server Error
}
} else if (isTimeoutError(err)) {
console.error(`Request timed out after ${err.timeoutMs}ms`);
} else if (isNetworkError(err)) {
console.error('Network disconnect or DNS failure:', err.message);
} else {
console.error('Unexpected error:', err);
}
}📜 API Reference
createNextHttp(config?: NextHttpConfig): NextHttp
Configuration Options:
| Parameter | Type | Default | Description |
|---|---|---|---|
| baseUrl | string | "" | Target base URL prepended to all endpoints |
| timeout | number | undefined | Request timeout in milliseconds (via AbortController) |
| headers | HeadersInit | {} | Default headers sent with each request |
| cache | RequestCache | undefined | Next.js fetch cache policy (force-cache, no-store, etc.) |
| next | NextFetchRequestConfig | undefined | Next.js App Router cache revalidation ({ revalidate, tags }) |
| retry | RetryConfig \| boolean | false | Exponential retry configuration or flag |
| responseType | 'json' \| 'text' \| 'blob' \| 'arrayBuffer' | 'json' | Response format parser |
| validateStatus| (status: number) => boolean | 200..299 | Custom status validation |
| before | BeforeHook[] | [] | Lifecycle hooks executed before request dispatch |
| after | AfterHook[] | [] | Lifecycle hooks executed after successful response |
| error | ErrorHook[] | [] | Lifecycle hooks executed on failure |
🤝 Contributing
Issues, discussions, and feature requests are welcome!
📄 License
MIT © Reza
