Guide

Fetch

Nitro provides a built-in fetch API that can be used to get data from server endpoints or from other sources. It's build on top of the unjs/ofetch.


Usage

In your handler, you've just to call the $fetch function to make a request. The response will be automatically parsed.

Router Handler
export default defineEventHandler(async (event) => {
  const data = await $fetch('https://ungh.cc/orgs/unjs/repos')

  return data
})

You can pass a generic type to the $fetch function to get a better type inference.

Router Handler
import { Repo } from '~/types'

export default defineEventHandler(async (event) => {
  const data = await $fetch<Repo[]>('https://ungh.cc/orgs/unjs/repos')

  return data
})

You can pass many options to the $fetch function like the method, headers, body, query, etc.

Router Handler
import { Repo } from '~/types'

export default defineEventHandler(async (event) => {
  const data = await $fetch<Repo[]>(' https://api.github.com/markdown', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: {
      text: 'Hello **world**!'
    }
  })

  return data
})

See more about the usage of the $fetch function in the unjs/ofetch documentation.

In-Server fetch

You can also use the $fetch function to make internal requests to other handlers.

Router Handler
export default defineEventHandler(async (event) => {
  const data = await $fetch('/api/users')

  return data
})

In reality, no fetch request is made and the handler is directly called thanks to unjs/unenv. This is useful to avoid making HTTP request overhead.