Integration with Next.js

Next.js is a web framework that allows you to build websites very quickly and feTS can be integrated with Next.js easily as an API middleware.

You can also consume the router in type-safe way by inferring router types from the server side.

Installation

npm i fets

Usage

We recommend to use feTS as a main middleware for your API routes. In this case, you should create a route.ts file under app/api/[...slug] directory. Since your base route is /api, you should configure base. Then you can create a router and export it as GET and POST methods.

import { createRouter, Response, Type } from 'fets'
 
export const router = createRouter({
  base: '/api'
}).route({
  method: 'GET',
  path: '/greetings',
  schemas: {
    responses: {
      200: Type.Object({
        message: Type.String()
      })
    }
  },
  handler: () => Response.json({ message: 'Hello World!' })
})
 
export { router as GET, router as POST }

Type-safe client usage

Then on the client side, you can use the type-safe client. You should import the router from the server side as a type, then you can create a client with the router type with endpoint option set to /api.

import { createClient } from 'fets'
import type router from './api/[...slug]/router'
 
const client = createClient<typeof router>({
  endpoint: '/api'
})
 
export default function Home({ greetingsResponse }: Props) {
  const [message, setMessage] = useState('')
  useEffect(() => {
    client['/greetings']
      .get()
      .then(res => res.json())
      .then(res => setMessage(res.message))
      .catch(err => setMessage(`Error: ${err.message}`))
  }, [])
  return (
    <div>
      <h1>Greetings Message from API: {greetingsResponse.message}</h1>
    </div>
  )
}

You can see the full example here.