Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: create a page on built-in fetch #2089

Merged
merged 6 commits into from
Jan 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 fetch-api instead of libraries such as axios because it's optimized for serverless environments and agnostic to the runtime.

::alert{type="info"}
You can keep using native `fetch()` if prefer.
::

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

## In-Server 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.