
Company News
Andrew Becherer Joins Socket as Chief Information Security Officer
Socket’s first CISO brings deep experience securing high-growth SaaS companies as open source supply chain threats accelerate.
@opensourceframework/next-circuit-breaker
Advanced tools
Circuit breaker pattern implementation for Next.js API routes - Prevent cascading failures by failing fast when downstream services are unavailable
Circuit breaker pattern implementation for Next.js API routes. Prevent cascading failures by failing fast when downstream services are unavailable.
npm install @opensourceframework/next-circuit-breaker
# or
yarn add @opensourceframework/next-circuit-breaker
# or
pnpm add @opensourceframework/next-circuit-breaker
import { CircuitBreaker } from '@opensourceframework/next-circuit-breaker';
// Create a circuit breaker for an external API call
const fetchUserData = async (userId: string) => {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) throw new Error('Failed to fetch user');
return response.json();
};
const breaker = new CircuitBreaker(fetchUserData, {
failureThreshold: 5, // Open after 5 failures
successThreshold: 2, // Close after 2 consecutive successes
timeout: 30000, // Wait 30s before trying again
});
// Use the circuit breaker
try {
const user = await breaker.fire('user-123');
console.log(user);
} catch (error) {
if (error.message === 'Circuit breaker is OPEN') {
// Handle the circuit being open
console.log('Service temporarily unavailable');
}
}
import { withApiCircuitBreaker } from '@opensourceframework/next-circuit-breaker';
import type { NextApiRequest, NextApiResponse } from 'next';
async function handler(req: NextApiRequest, res: NextApiResponse) {
// Your API logic that calls external services
const data = await fetchExternalService();
res.status(200).json(data);
}
// Wrap your handler with circuit breaker protection
export default withApiCircuitBreaker(handler, {
failureThreshold: 5,
timeout: 30000,
onOpen: () => console.log('Circuit opened - external service may be down'),
onClose: () => console.log('Circuit closed - service recovered'),
});
import { withCircuitBreaker } from '@opensourceframework/next-circuit-breaker';
// Wrap any async function
const protectedFetch = withCircuitBreaker(
async (url: string) => {
const response = await fetch(url);
return response.json();
},
{
failureThreshold: 3,
timeout: 10000,
}
);
// Use like a normal function
const data = await protectedFetch('/api/data');
CircuitBreakerThe main circuit breaker class.
new CircuitBreaker<TArgs, TResult>(
request: AsyncFunction<TArgs, TResult>,
options?: CircuitBreakerOptions
)
| Option | Type | Default | Description |
|---|---|---|---|
failureThreshold | number | 3 | Number of failures before opening the circuit |
successThreshold | number | 2 | Number of successes before closing the circuit |
timeout | number | 10000 | Time in ms before attempting to close |
onOpen | () => void | - | Callback when circuit opens |
onClose | () => void | - | Callback when circuit closes |
onHalfOpen | () => void | - | Callback when circuit enters half-open |
| Method | Description |
|---|---|
fire(...args) | Execute the wrapped function |
getState() | Get current state: 'CLOSED', 'OPEN', 'HALF_OPEN' |
getStats() | Get detailed state information |
isOpen() | Check if circuit is open |
isClosed() | Check if circuit is closed |
isHalfOpen() | Check if circuit is half-open |
trip() | Manually open the circuit |
reset() | Manually reset to closed state |
withCircuitBreakerConvenience function to wrap an async function.
withCircuitBreaker<TArgs, TResult>(
handler: AsyncFunction<TArgs, TResult>,
options?: CircuitBreakerOptions
): (...args: TArgs) => Promise<TResult>
withApiCircuitBreakerAlias for withCircuitBreaker - use in Next.js API routes.
The circuit breaker has three states:
CLOSED (Normal Operation)
failureThreshold, circuit opensOPEN (Failing Fast)
timeout milliseconds, circuit enters half-open stateHALF_OPEN (Testing Recovery)
successThreshold consecutive requests succeed, circuit closesconst breaker = new CircuitBreaker(fetchData, {
failureThreshold: 5,
timeout: 30000,
onOpen: () => {
// Send alert to monitoring
logger.error('Circuit opened for fetchData');
},
onClose: () => {
logger.info('Circuit closed - service recovered');
},
});
// With fallback
try {
return await breaker.fire(id);
} catch (error) {
if (breaker.isOpen()) {
// Return cached data or default
return getCachedData(id);
}
throw error;
}
See Contributing Guide for details.
MIT © OpenSource Framework Contributors
FAQs
Circuit breaker pattern implementation for Next.js API routes - Prevent cascading failures by failing fast when downstream services are unavailable
We found that @opensourceframework/next-circuit-breaker demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Company News
Socket’s first CISO brings deep experience securing high-growth SaaS companies as open source supply chain threats accelerate.

Company News
Replit is integrating Socket Firewall into its AI-powered development experience to help protect builders from malicious open source packages.

Security News
npm confirmed a tooling bug incorrectly marked several one-character packages as security holders and said it was working on a rollback.