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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zodified-api/next

v2.2.0

Published

Next.js integration for ZodifiedAPI

Downloads

200

Readme

@zodified-api/next

@zodified-api/next is an extension for ZodifiedAPI that provides seamless integration with Next.js. It allows you to create type-safe APIs using ZodifiedAPI's robust validation and handling mechanisms while leveraging the powerful features of Next.js.

Features

  • Type Safety: Ensures type safety across your Next.js API routes.
  • Zod Integration: Utilizes Zod for schema validation, ensuring consistent data validation.
  • Next.js Compatibility: Works seamlessly with both the App Router and Pages Router in Next.js.
  • Mocking Support: Leverage the useMock feature to simulate API responses in your Next.js API routes, ideal for testing and development.
  • Middleware Support: Easily add and manage middleware for your API routes.
  • Fetch-Based Implementation: Unlike Zodios, this library wraps around fetch instead of axios.

Installation

You can install the package via npm:

npm install @zodified-api/next

or via yarn:

yarn add @zodified-api/next

Usage

1. Define Your API Configuration

First, use zod to define your API configuration and schema validation.

import { z } from 'zod';
import { makeApi, makeEndpoint } from '@zodified-api/core';

// Define a schema for the user object
const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

// Define a 'getUser' endpoint
const getUser = makeEndpoint({
  method: 'get',
  path: '/user',
  alias: 'getUser',
  description: 'Fetch a user by ID',
  parameters: [
    {
      type: 'Query',
      name: 'id',
      schema: z.number(),
      description: 'User ID',
    },
  ],
  response: userSchema,
  customProperties: {
    authRequired: true,
  },
});

// Combine all endpoints into a single API configuration
export const api = makeApi([getUser]);

2. Create a Next.js API Route

Use the NextJsAppRouter or NextJsPagesRouter classes to create a type-safe API route that integrates with Next.js.

Example with the Next.js App Router

import { Method, findEndpointByMethodAndPath } from '@zodified-api/core';
import { NextJsAppRouter } from '@zodified-api/next';
import { api } from '@/api'; // Your API configuration file
import type { NextRequest } from 'next/server';

// Define the request handler for the '/user' endpoint
const handler = async (req) => {
  const user = { id: 1, name: 'John Doe' };
  return user;
};

// Initialize the Next.js API router with the defined API configuration
const router = new NextJsAppRouter(api);

// Add middleware to the router
router.use((req, res, next) => {
  const { method, nextUrl } = req;
  const endpoint = findEndpointByMethodAndPath(
    api,
    method.toLowerCase() as Method,
    nextUrl.pathname as any, // Cast pathname to any to satisfy type checks
  );

  if (!endpoint) {
    throw new Error('Endpoint not found');
  }

  if (endpoint.customProperties.authRequired) {
    throw new Error('Unauthorized');
  }

  next();
});

// Export the GET handler for the '/user' route
export const GET = router.handleAppRoute('get', '/user', handler);

Explanation

  1. API Request Handler:

    • The handler function processes incoming API requests and returns a user object.
    • The findEndpointByMethodAndPath function is used to retrieve endpoint metadata, such as custom properties.
  2. Middleware Integration:

    • Middleware is used to check if the requested endpoint requires authentication. If the endpoint is not found or if authentication is required and not provided, an error is thrown.
  3. NextJsAppRouter and NextJsPagesRouter:

    • NextJsAppRouter is used for handling API routes in the Next.js App Router.
    • The handleAppRoute method connects the handler function to the appropriate HTTP method and path, ensuring clean, organized, and type-safe API route management within a Next.js project.

API Reference

NextJsAppRouter

A class that extends ZodifiedAPI's server capabilities to integrate with Next.js.

  • Methods:
    • handleAppRoute<M extends Method, Path extends ZodifiedPathsByMethod<Api, M>>( method: M, path: Path, handler: ZodifiedHandler<Api, M, Path, NextRequestAdapter, NextResponseAdapter> ): Handles a specific API endpoint in the Next.js App Router.
    • use(middleware: (req: NextRequestAdapter, res: NextResponseAdapter, next: () => void) => void): Adds middleware to the router.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request or open an Issue on the GitHub repository.

License

This project is licensed under the MIT License.