Fetcher
Type-safe API data fetching with RPC-style interface
The VitNode fetcher provides a type-safe RPC (Remote Procedure Call) style interface for making API requests. It simplifies data fetching by providing strong typing and a consistent API across your application.
Server-side only
The fetcher()
function can only be used on the server-side. Client-side
usage is not supported.
Getting Started
First, import the required dependencies:
import { fetcher } from '@vitnode/core/lib/fetcher';
import { usersModule } from '@vitnode/core/api/modules/users/users.module';
Make your first API call:
const response = await fetcher(usersModule, {
path: '/session',
method: 'get',
module: 'users',
});
// Handle the response
if (response.ok) {
const data = await response.json();
console.log('Session data:', data);
}
The fetcher returns a standard Response object, just like the native fetch
API. This makes it familiar and easy to work with.
Advanced Features
Path Prefixing
When working with nested modules you can import the module and use it directly with the fetcher
function and add the prefixPath
option to specify a path prefix. This is useful for organizing your API endpoints and keeping them modular.
const response = await fetcher(categoriesAdminModule, {
prefixPath: '/admin', // Adds prefix to the path
path: '/categories',
method: 'post',
module: 'categories',
args: {
body: {
name: 'Technology',
description: 'Tech-related articles',
},
},
});
// This will make a request to: /admin/categories
Caching Responses
You can leverage Next.js caching by passing cache options:
const response = await fetcher(usersModule, {
path: '/session',
method: 'get',
module: 'users',
options: {
cache: 'force-cache', // Uses Next.js cache
},
});
Cookie Management
When working with authentication or sessions, you might need to handle cookies. React Server Components have special considerations for cookie handling:
Cookie Handling
Cookie saving is only supported for requests that return a 2xx status code.
Here's how to enable cookie handling for a sign-in request:
const response = await fetcher(usersModule, {
path: '/sign_in',
method: 'post',
module: 'users',
allowSaveCookies: true,
args: {
body: {
email: 'user@example.com',
password: '********',
},
},
});