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/lib/fetcher';
import { usersModule } from 'vitnode/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

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
  },
});

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: '********',
    },
  },
});

On this page