VergeStackVergeStack

Introduction

Welcome to the @vergestack/api documentation

Overview

VergeStack API provides utilities to define and consume server actions with end-to-end type safety. Server and client logic share type information, reducing the likelihood of runtime errors and improving overall code quality. In addition to server action support, VergeStack API offers first class support for defining traditional HTTP endpoints (Next.js routes).

Features

  1. Type Safety and Validation: Define input and output schemas using zod for robust type checking.
  2. Server-Side Helpers: Easily create actions and routes with createAction and createRoute functions.
  3. Client-Side Integration: Integrate the useAction hook to manage mutations within components.

Defining Endpoints

Server actions and routes in VergeStack are defined using the createAction and createRoute functions, respectively. These functions allow you to specify input and output schemas using the zod library, ensuring that your server-side logic is type-safe and validated. Below are examples of how to define a server action and a route that generate greeting messages based on the provided input.

'use server';
 
import { createAction } from '@vergestack/api';
import { z } from 'zod';
 
export const greetingAction = createAction()
  .input(z.string())
  .output(z.string())
  .handler(async ({ input }) => {
    return `Hello, ${input}!`;
  });

Using Endpoints

Once you have defined a server action or route handler, you can call it from a client-side component. Below is an example of how to use the greetingAction and POST route in a client-side component.

import { useAction } from '@vergestack/api-react';
import { greetingAction } from './actions';
 
export const ActionComponent = () => {
  const { handlers, data, error } = useAction(greetingAction);
 
  return (
    <div>
      <form {...handlers}>
        <input type="text" name="name" />
        <button type="submit">Generate Greeting</button>
      </form>
      {data && <p>Response: {data}</p>}
      {error && <p>Error: {error}</p>}
    </div>
  );
};

FAQ

What is an endpoint?

An endpoint is a function defined with the createAction or createRoute functions.

What is the difference between createAction and createRoute?

createAction is used to define server actions, which are functions that can be called from the client-side. These are best for creating server-side logic that needs to be executed in response to a client-side action, such as form submission.

createRoute is used to define server routes, which are traditional REST API endpoints (GET, POST, PUT, DELETE). These are useful for creating APIs that can be consumed by external services, such as API clients or webhooks.

On this page