npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

next-query-portal

v1.0.0

Published

Next.js portal

Readme

Next Portal

Next Portal is a unified API client library designed for React applications. It provides type-safe API interactions with built-in caching, request deduplication, and seamless form integration.

Features

  • 🔒 Type-Safe: Define your API endpoints with Zod schemas for bulletproof type safety.
  • 🚀 Simple to Use: Intuitive hooks like useQuery and useMutation for easy data fetching.
  • ⚡️ Fast by Default: Built-in caching, request deduplication, and stale-while-revalidate.
  • 🔌 Framework Agnostic: Works with Next.js, Create React App, React Native, and more.
  • 🧪 Testable: Mock data providers for easy testing without a database.

Installation

npm install @open-eats/next-portal
# or
yarn add @open-eats/next-portal

Quick Start

Step 1: Initialize the library

// src/lib/api.ts
import { initApiLibrary } from '@open-eats/next-portal';

// For production with Prisma:
initApiLibrary();

// For testing with mock data:
initApiLibrary({ 
  useMockProvider: true,
  mockData: {
    // Optional mock data
  }
});

Step 2: Define your endpoints

// src/lib/endpoints.ts
import { z } from 'zod';
import { createEndpoint, UserRoleValue } from '@open-eats/next-portal';

// Define your schema
const userSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email()
});

// Create an endpoint
export const getUsersEndpoint = createEndpoint({
  description: "Get all users",
  method: "GET", 
  path: ["api", "users"],
  responseSchema: z.array(userSchema),
  roles: [UserRoleValue.ADMIN]
});

Step 3: Use the hooks in your components

// src/components/UsersList.tsx
import { useQuery } from '@open-eats/next-portal';
import { getUsersEndpoint } from '../lib/endpoints';

function UsersList() {
  const { data, isLoading, error } = useQuery(getUsersEndpoint);
  
  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  
  return (
    <ul>
      {data?.map(user => (
        <li key={user.id}>{user.name} ({user.email})</li>
      ))}
    </ul>
  );
}

Complete Example

Here's a complete example showing a data fetching and form submission workflow:

import { z } from 'zod';
import { createEndpoint, useQuery, useMutation, useApiForm, UserRoleValue } from '@open-eats/next-portal';

// 1. Define your schemas
const userSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email()
});

const createUserSchema = userSchema.omit({ id: true });
type User = z.infer<typeof userSchema>;
type CreateUser = z.infer<typeof createUserSchema>;

// 2. Define your endpoints
const getUsersEndpoint = createEndpoint({
  description: "Get all users",
  method: "GET",
  path: ["api", "users"],
  responseSchema: z.array(userSchema),
  roles: [UserRoleValue.ADMIN]
});

const createUserEndpoint = createEndpoint({
  description: "Create user", 
  method: "POST",
  path: ["api", "users"],
  requestSchema: createUserSchema,
  responseSchema: userSchema,
  roles: [UserRoleValue.ADMIN]
});

// 3. Create your component
function UsersPanel() {
  // Fetch users
  const { 
    data: users, 
    isLoading,
    refetch
  } = useQuery(getUsersEndpoint);

  // Create a form with validation
  const {
    register,
    handleSubmit,
    formState: { errors },
    submitForm,
    isSubmitting,
    formError
  } = useApiForm<User, CreateUser>(
    createUserEndpoint,
    { defaultValues: { name: '', email: '' } },
    { 
      onSuccess: () => refetch(),
      invalidateQueries: ['users']
    }
  );

  // Form submission handler
  const onSubmit = handleSubmit(data => submitForm(data));

  return (
    <div>
      <h1>Users</h1>
      
      {/* Display users */}
      {isLoading ? (
        <p>Loading...</p>
      ) : (
        <ul>
          {users?.map(user => (
            <li key={user.id}>{user.name} - {user.email}</li>
          ))}
        </ul>
      )}

      {/* Create user form */}
      <form onSubmit={onSubmit}>
        <div>
          <label>
            Name:
            <input {...register('name', { required: true })} />
            {errors.name && <span>Name is required</span>}
          </label>
        </div>
        
        <div>
          <label>
            Email:
            <input type="email" {...register('email', { required: true })} />
            {errors.email && <span>Valid email is required</span>}
          </label>
        </div>
        
        <button type="submit" disabled={isSubmitting}>
          {isSubmitting ? 'Creating...' : 'Create User'}
        </button>
        
        {formError && <div className="error">{formError.message}</div>}
      </form>
    </div>
  );
}

Advanced Usage

Custom Data Provider

import { initApiLibrary, DataProvider } from '@open-eats/next-portal';

// Create a custom data provider
class MyCustomDataProvider implements DataProvider {
  async getUserRoles(userId: string) {
    // Custom implementation for getting user roles
    return [];
  }
  
  // Additional custom methods
  async getCustomData() {
    // ...
  }
}

// Initialize with your custom provider
initApiLibrary({
  dataProvider: new MyCustomDataProvider()
});

Global Error Handling

import { initApiLibrary } from '@open-eats/next-portal';

initApiLibrary({
  errorHandler: (error, context) => {
    console.error(`Error in ${context}:`, error);
    // Send to error tracking service, show notification, etc.
  }
});

Optimistic Updates

const { mutate } = useMutation(updateUserEndpoint, {
  updateQueries: [
    {
      queryKey: ['users'],
      updater: (oldData, newData) => {
        // Update the cached data optimistically
        return oldData.map(user => 
          user.id === newData.id ? newData : user
        );
      }
    }
  ]
});

API Reference

Visit our API documentation for complete details on all available options and configurations.

License

MIT