Skip to content

Commit

Permalink
docs: create a page on built-in fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
Barbapapazes committed Jan 16, 2024
1 parent cdb0ee4 commit 8d84071
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions docs/content/1.guide/6.fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
icon: i-ri-global-line
---

# 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](https://ofetch.unjs.io) package.

This is important to use it instead of the built-in Node `fetch` or Axios because it's optimized for serverless environments and agnostic to the runtime.

::alert{type="info"}
We **do not overwrite** the built-in `fetch` function, so you can still use it if you want.
::

## Usage

In you handler, you've just to call the `$fetch` function to make a request. Automatically, the response will be smartly parsed using [unjs/destr](https://destr.unjs.io).

```ts [Router Handler]
export default defineEventHandler(async (event) => {
const data = await $fetch('https://api.github.com/orgs/unjs/repos')

return data
})
```

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

```ts [Router Handler]
import { Repo } from '~/types'

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

return data
})
```

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

```ts [Router Handler]
import { Repo } from '~/types'

export default defineEventHandler(async (event) => {
const data = await $fetch<Repo[]>('https://api.github.com/orgs/unjs/repos', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
name: 'my-repo'
}
})

return data
})
```

See more about the usage of the `$fetch` function in the [unjs/ofetch](https://ofetch.unjs.io) documentation.

## Internal Fetch

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

```ts [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](https://unenv.unjs.io). This is useful to avoid making HTTP requests and to slow down your application.

0 comments on commit 8d84071

Please sign in to comment.