
Product
Introducing Socket MCP for Claude Desktop
Add secure dependency scanning to Claude Desktop with Socket MCP, a one-click extension that keeps your coding conversations safe from malicious packages.
next-netkit
Advanced tools
Next-Netkit is a lightweight, injectable network manager built on top of Axios, designed to work seamlessly with Clean Architecture and dependency injection frameworks like Inversify. This package is ideal for both TypeScript and JavaScript projects and supports test-driven development (TDD) by making network interactions mockable and testable.
Inversify
for clean and testable architecture.ApiException
class.You can find the changelog here.
npm install next-netkit axios inversify
You can create an instance of NetworkManager by passing the base URLs, mode (development or production), Axios configuration options, and error-handling parameters.
import { NetworkErrorParams, NetworkManager } from "next-netkit";
// Define your error-handling parameters
const networkErrorParams: NetworkErrorParams = {
messageKey: "message",
statusCodeKey: "status",
couldNotParseError: "Could not parse error",
jsonIsEmptyError: "JSON is empty",
noInternetError: "No internet connection",
jsonNullError: "JSON is null",
jsonUnsupportedObjectError: "JSON is unsupported object",
notMapTypeError: "Not map type",
};
/// In here NODE_ENV is an environment variable that is set to 'production' or 'development'
/// It may differ according to your project setup
const isTestMode = process.env.NODE_ENV !== "production";
// Create a new instance of NetworkManager
const networkManagerInstance = new NetworkManager({
baseUrl: "https://api.example.com", // Production base URL
devBaseUrl: "https://dev.example.com", // Development base URL
testMode: isTestMode, // Test mode: false (production), true (development)
baseOptions: {}, // Axios config options
errorParams: networkErrorParams, // Error parameters
withCredentials: true,
refreshTokenPath: "api/auth/refresh-token",
});
request
is used to fetch or send data where a single response model is expected.
// Example GET request to fetch a single model
const product = await networkManager.request<ProductModel>({
method: RequestMethod.GET,
url: "/api/product/1",
});
/// response.data is of type BookEntity
// Example POST request and get response
const signInResponse = await networkManager.request<SignInResponseDto>({
method: RequestMethod.POST,
url: "/api/auth/sign-in",
data: signInRequestDto,
});
/// signInResponse.data is of type SignInResponseDto
requestList
is used when you expect the API to return an array of items.
// Example GET request to fetch a list of products
const products = await networkManager.requestList<ProductModel>({
method: RequestMethod.GET,
url: "/api/v1/products",
});
/// response.data is of type ProductModel[]
This method ensures the response is an array and throws an error if a non-list is returned.
requestVoid
is used for requests where no data is expected in return (e.g., DELETE or POST
operations that don't return any data).
// Example DELETE request with no response body expected
await networkManager.requestVoid({
method: RequestMethod.DELETE,
url: "/api/v1/products/1",
});
The NetworkManager automatically handles token refresh when an access token expires. You only need to provide the API endpoint where the refresh token request is made. Once the access token expires, the manager will automatically request a new one and retry the failed request with the new token.
const networkManagerInstance = new NetworkManager({
// Other options (e.g., baseUrl, etc.)
refreshTokenPath: "api/auth/refresh-token", // Path to the backend refresh token API
});
In some scenarios, you may want to ensure that an access token is refreshed before making a request, particularly for actions that cannot be repeated easily without potential issues.
This feature requires that the refreshTokenPath
is correctly configured in the NetworkManager
settings. Without it, token refresh functionality will not work.
Here’s an example of how to make such a request in TypeScript:
const product = await networkManager.request<ProductModel>({
method: RequestMethod.GET,
url: "/api/product/1",
isTokenRefreshRequired: true, // Ensure token refresh is triggered before the request
});
Using the Clean Architecture, you can create a RemoteDataSource
class that implements an
interface, which can be injected into your repository class.
/// src/feature-name/data/datasources/i-auth-remote-datasource.ts
export interface IAuthRemoteDataSource {
signIn(signInDto: SignInDto): Promise<SignInResponseDto>;
}
/// src/feature-name/data/datasources/auth-remote-datasource.ts
@injectable()
export class AuthRemoteDataSource implements IAuthRemoteDataSource {
constructor(@inject("INetworkManager") private networkManager: INetworkManager) {}
async signIn(dto: SignInDto): Promise<SignInResponseDto> {
return await this.networkManager.request<SignInResponseDto>({
method: RequestMethod.POST,
url: `/api/auth/sign-in`,
data: dto,
});
}
}
Now, you can inject the IAuthRemoteDataSource
into your repository class and use it to make
network requests.
/// src/feature-name/data/repositories/auth-repository.ts
@injectable()
export class AuthRepository implements IAuthRepository {
constructor(
@inject("IAuthRemoteDataSource") private remoteDataSource: IAuthRemoteDataSource,
@inject("IAuthLocalDataSource") private localDataSource: IAuthLocalDataSource
) {}
async signIn(dto: SignInDto): Promise<void> {
try {
const response = await this.remoteDataSource.signIn(dto);
this.localDataSource.saveUser(response.user);
} catch (error) {
throw error;
}
}
}
Next-Netkit
works seamlessly with Inversify
to enable dependency injection. Here’s how you can
set
it up:
Create a module for the network manager using Inversify
.
// network.container.ts
import { ContainerModule, interfaces } from "inversify";
import { INetworkManager, NetworkManager, NetworkErrorParams } from "next-netkit";
const networkManagerInstance = new NetworkManager({
baseUrl: "https://api.example.com", // Production base URL
devBaseUrl: "https://dev.example.com", // Development base URL
testMode: isTestMode, // Test mode: false (production), true (development)
baseOptions: {}, // Axios config options
errorParams: networkErrorParams, // Error parameters
withCredentials: true,
refreshTokenPath: "api/auth/refresh-token",
});
// Create a network container module
const networkContainer = new ContainerModule((bind: interfaces.Bind) => {
bind<INetworkManager>("INetworkManager").toConstantValue(networkManagerInstance);
});
export { networkContainer };
You can merge multiple containers, including the network container, like so:
// main.container.ts
import { Container } from "inversify";
import { authContainer } from "./auth/auth.container";
import { networkContainer } from "./network.container";
const container = new Container();
// Merge containers
container.load(authContainer);
container.load(networkContainer);
export { container };
This project is licensed under the MIT License. See the LICENSE file for details.
[0.9.1]
FAQs
Network manager
The npm package next-netkit receives a total of 3 weekly downloads. As such, next-netkit popularity was classified as not popular.
We found that next-netkit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers 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.
Product
Add secure dependency scanning to Claude Desktop with Socket MCP, a one-click extension that keeps your coding conversations safe from malicious packages.
Product
Socket now supports Scala and Kotlin, bringing AI-powered threat detection to JVM projects with easy manifest generation and fast, accurate scans.
Application Security
/Security News
Socket CEO Feross Aboukhadijeh and a16z partner Joel de la Garza discuss vibe coding, AI-driven software development, and how the rise of LLMs, despite their risks, still points toward a more secure and innovative future.