• This repository has been archived on 28/Nov/2023
  • Stars
    star
    593
  • Rank 75,443 (Top 2 %)
  • Language
    TypeScript
  • Created over 2 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Intuitive data fetching for Next.js

Next Fetch

Think in React, instead about routing: Next Fetch is an intuitive way to dynamically fetch data from API endpoints in Next.js, using your favorite libraries.

πŸ’ƒ Import your API endpoints instead of making a stringified dance

πŸ”’ Infer the types end-to-end for your data based on its implementation

βš› Think in React, instead of routing: you only export a React hook!

πŸ•΅ Embrace best-practices: input validation, error handling, etc.

🌐 Use Request and Response classes as building blocks, no matter what runtime you're running on (Node.js or Edge)

πŸ“ Use <Form /> component for making progressive enhanced experiences

🀯 Supports SWR and React Query out of the box!

What does that mean?

Next Fetch is using compile-time transformations to allow you to import your API endpoints instead of referencing them as plain strings, while keeping the type definitions co-located with the implementation.

Next.js + Next Fetch Plain Next.js
API implementation
// pages/api/message.swr.tsx
import { query } from "@next-fetch/swr";
import z from "zod";

export const useMessage = query(
  // use zod for input validation
  z.object({
    name: z.string(),
  }),
  async function ({ name }) {
    // this.request is a `Request` instance
    return { hello: `world, ${name}` };
  }
);
// pages/api/message.tsx
import type { NextApiRequest, NextApiResponse } from "next";

export default (req: NextApiRequest, res: NextApiResponse) => {
  // ad-hoc input validation
  const name = Array.isArray(req.query.name)
    ? req.query.name[0]
    : req.query.name;
  if (!name) {
    return res.status(400).json({ error: "No name provided" });
  }

  // explicit type defniitions required
  return res.status(200).json({ hello: `world, ${name}` });
};
API consumption
import { useMessage } from "./api/message";

export default function MyPage() {
  const { data, error } = useMessage({
    // will autocomplete and
    // type-check the input arguments
    name: "John Doe",
  });

  // autocompletes and type-checks!
  const hello = data?.hello;

  return <div>{/* ... */}</div>;
}
// pages/index.tsx
import useSWR from "swr";

const fetcher = (url: string) => {
  const response = await fetch(url);

  // handle input validation or runtime errors
  if (!response.ok) {
    const text = await response.text().catch(() => null);
    throw new Error(`response is not okay${text ? `: ${text}` : ""}`);
  }

  return await response.json();
};

export default function MyPage() {
  const { data, error } = useSWR("/api/message?name=John%20Doe", fetcher);
  /** `data` is `any`, so we need to explicitly type-cast here */
  return <div>{/* ... */}</div>;
}

More Repositories

1

gemini-chatbot

Build your own generative UI chatbot using the Vercel AI SDK and Google Gemini
TypeScript
673
star
2

slacker

A bot that notifies you on Slack whenever your company/product is mentioned on Hacker News. Powered by Vercel Functions & Upstash.
TypeScript
341
star
3

react-on-the-edge

Server-rendered React using Vercel Edge Functions.
TypeScript
219
star
4

app-router-auth

Auth patterns using Next.js App Router
TypeScript
212
star
5

function-database-latency

Visualize the latency of databases from Vercel Functions.
JavaScript
171
star
6

semantic-image-search

Semantic Image Search with Vercel AI SDK
TypeScript
118
star
7

ai-sdk-preview-rag

TypeScript
110
star
8

ai-sdk-preview-rsc-genui

Generative UI with React Server Components and Vercel AI SDK
TypeScript
101
star
9

rsc-llm-on-the-edge

TypeScript
100
star
10

remix-on-the-edge

Remix running on Vercel Edge Functions
TypeScript
82
star
11

ai-sdk-preview-use-object

TypeScript
35
star
12

ai-sdk-preview-multi-steps

TypeScript
29
star
13

ai-sdk-preview-attachments

TypeScript
27
star
14

next-on-the-edge

TypeScript
21
star
15

remix-platforms

Multi-tenant Remix application (multiple custom domains with a single codebase)
CSS
13
star
16

ai-sdk-flags-edge-config

Example project showing how you can use Edge Config and Feature Flags with the Vercel AI SDK
TypeScript
12
star
17

blue-green

TypeScript
12
star
18

ai-sdk-preview-array-output-mode

TypeScript
10
star
19

react-spa

A React SPA with Express
JavaScript
7
star
20

next-spa-drizzle

https://next-spa-drizzle.vercel.app/
TypeScript
3
star
21

vercel-nav-demo

v0 + Shadcn UI version
TypeScript
3
star
22

ai-sdk-deployment-guide

TypeScript
3
star
23

without-react-tweet-iframes

TypeScript
2
star