### Install @fastify/fetch Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Install the package using npm. No additional setup is required for basic usage. ```bash npm install @fastify/fetch ``` -------------------------------- ### Basic Fastify Fetch Usage Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Register the plugin and define fetch handlers for GET and POST requests. This example demonstrates setting up a Fastify server with the fetch plugin and defining two simple routes. ```javascript import Fastify from 'fastify' import fastifyFetch from '@fastify/fetch' const fastify = Fastify() await fastify.register(fastifyFetch) fastify.fetch.get('/hello', async (request, ctx) => { ctx.log.info('handling request') return new Response('Hello World') }) fastify.fetch.post('/data', async (request, ctx) => { const body = await request.json() return Response.json({ received: body }) }) await fastify.listen({ port: 3000 }) ``` -------------------------------- ### Custom Headers Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Example of setting custom headers in a fetch response. ```APIDOC ### Custom Headers ```javascript fastify.fetch.get('/data', async (request, ctx) => { return new Response('data', { headers: { 'X-Custom-Header': 'value', 'Cache-Control': 'max-age=3600' } }) }) ``` ``` -------------------------------- ### Using Query Parameters Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Example of accessing query parameters in a fetch handler. ```APIDOC ### Using Query Parameters ```javascript fastify.fetch.get('/search', async (request, ctx) => { const { q, limit } = ctx.query const results = await search(q, parseInt(limit)) return Response.json(results) }) ``` ``` -------------------------------- ### JSON Response Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Example of returning a JSON response from a fetch handler. ```APIDOC ### JSON Response ```javascript fastify.fetch.get('/users/:id', async (request, ctx) => { const user = await getUser(ctx.params.id) return Response.json(user) }) ``` ``` -------------------------------- ### Reading Request Body Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Examples of how to read different types of request bodies within a fetch handler. ```APIDOC ### Reading Request Body ```javascript fastify.fetch.post('/upload', async (request, ctx) => { // JSON const json = await request.json() // Text const text = await request.text() // FormData const formData = await request.formData() // ArrayBuffer const buffer = await request.arrayBuffer() return new Response('OK') }) ``` ``` -------------------------------- ### Fastify Fetch Hooks Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Demonstrates how to use Fastify's built-in hooks with routes registered via @fastify/fetch. Hooks like onRequest and onResponse can be utilized. ```javascript fastify.addHook('onRequest', async (request, reply) => { // runs before the fetch handler }) fastify.addHook('onResponse', async (request, reply) => { // runs after the response is sent }) ``` -------------------------------- ### Accessing Request URL Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Example of how to access and parse the request URL within a fetch handler. ```APIDOC ### Accessing Request URL ```javascript fastify.fetch.get('/info', async (request, ctx) => { const url = new URL(request.url) return Response.json({ pathname: url.pathname, search: url.search }) }) ``` ``` -------------------------------- ### fastify.fetch.get(path, handler) Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a GET route. The handler receives a Web Standard `Request` and a `FetchContext` object, and must return a Web Standard `Response`. ```APIDOC ## `fastify.fetch.get(path, handler)` Register a GET route. The handler receives a Web Standard `Request` and a `FetchContext` object, and must return a Web Standard `Response`. ```javascript fastify.fetch.get('/users/:id', async (request, ctx) => { // ctx.params holds route parameters const userId = ctx.params.id // Use the Web Standard URL API on the request object const url = new URL(request.url) ctx.log.info({ userId, path: url.pathname }, 'fetching user') const user = await db.findUser(userId) if (!user) { return new Response(JSON.stringify({ error: 'Not found' }), { status: 404, headers: { 'content-type': 'application/json' } }) } return Response.json(user) // → 200 { "id": "42", "name": "Jane Doe" } }) ``` ``` -------------------------------- ### JSON Response Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Returns a JSON response from a fetch handler. Ensure the data is serializable to JSON. This example retrieves a user by ID and returns their data. ```javascript fastify.fetch.get('/users/:id', async (request, ctx) => { const user = await getUser(ctx.params.id) return Response.json(user) }) ``` -------------------------------- ### Register GET Route with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a GET route using fastify.fetch.get. The handler receives a Web Standard Request and FetchContext, and must return a Web Standard Response. Access route parameters via ctx.params and use standard URL APIs. ```javascript fastify.fetch.get('/users/:id', async (request, ctx) => { // ctx.params holds route parameters const userId = ctx.params.id // Use the Web Standard URL API on the request object const url = new URL(request.url) ctx.log.info({ userId, path: url.pathname }, 'fetching user') const user = await db.findUser(userId) if (!user) { return new Response(JSON.stringify({ error: 'Not found' }), { status: 404, headers: { 'content-type': 'application/json' } }) } return Response.json(user) // → 200 { "id": "42", "name": "Jane Doe" } ``` -------------------------------- ### Custom Headers Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Sets custom headers on the Response object. This is useful for controlling caching or providing metadata. ```javascript fastify.fetch.get('/data', async (request, ctx) => { return new Response('data', { headers: { 'X-Custom-Header': 'value', 'Cache-Control': 'max-age=3600' } }) }) ``` -------------------------------- ### Custom Status Code Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Example of returning a custom status code in a fetch response. ```APIDOC ### Custom Status Code ```javascript fastify.fetch.post('/users', async (request, ctx) => { const body = await request.json() const user = await createUser(body) return Response.json(user, { status: 201 }) }) ``` ``` -------------------------------- ### Custom Status Code Example Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Returns a response with a custom HTTP status code. The `status` option in the Response constructor allows specifying codes other than 200. ```javascript fastify.fetch.post('/users', async (request, ctx) => { const body = await request.json() const user = await createUser(body) return Response.json(user, { status: 201 }) }) ``` -------------------------------- ### fastify.fetch.post(path, handler) Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a POST route. Use `request.json()`, `request.text()`, `request.formData()`, or `request.arrayBuffer()` to read the body. ```APIDOC ## `fastify.fetch.post(path, handler)` Register a POST route. Use `request.json()`, `request.text()`, `request.formData()`, or `request.arrayBuffer()` to read the body. ```javascript fastify.fetch.post('/users', async (request, ctx) => { const body = await request.json() // body → { name: 'Alice', email: 'alice@example.com' } const created = await db.createUser(body) return Response.json({ id: created.id, name: created.name }, { status: 201 }) // → 201 { "id": "99", "name": "Alice" } }) ``` ``` -------------------------------- ### Register @fastify/fetch Plugin Source: https://context7.com/fastify/fastify-fetch/llms.txt Register the @fastify/fetch plugin to enable the fastify.fetch namespace. Ensure Fastify v5 or later is used. ```javascript import Fastify from 'fastify' import fastifyFetch from '@fastify/fetch' const fastify = Fastify({ logger: true }) await fastify.register(fastifyFetch) // fastify.fetch is now available fastify.fetch.get('/ping', async (request, ctx) => { return new Response('pong') }) await fastify.listen({ port: 3000 }) // GET http://localhost:3000/ping → 200 "pong" ``` -------------------------------- ### Plugin Registration Source: https://context7.com/fastify/fastify-fetch/llms.txt Register the @fastify/fetch plugin with your Fastify instance. After registration, the `fastify.fetch` namespace becomes available for registering routes. ```APIDOC ## Plugin Registration Register `@fastify/fetch` as a Fastify plugin using `fastify.register()`. ```javascript import Fastify from 'fastify' import fastifyFetch from '@fastify/fetch' const fastify = Fastify({ logger: true }) await fastify.register(fastifyFetch) // fastify.fetch is now available fastify.fetch.get('/ping', async (request, ctx) => { return new Response('pong') }) await fastify.listen({ port: 3000 }) // GET http://localhost:3000/ping → 200 "pong" ``` ``` -------------------------------- ### Fastify Hooks Integration Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Routes registered with `fastify.fetch.*` support all standard Fastify hooks. ```APIDOC ### Hooks Routes registered with `fastify.fetch.*` are standard Fastify routes, so all Fastify hooks are supported: | Hook | Fires | |------|-------| | `onRequest` | Yes | | `preParsing` | Yes | | `preValidation` | Yes | | `preHandler` | Yes | | `onSend` | Yes | | `onResponse` | Yes | | `onError` | Yes (on errors) | ```javascript fastify.addHook('onRequest', async (request, reply) => { // runs before the fetch handler }) fastify.addHook('onResponse', async (request, reply) => { // runs after the response is sent }) ``` ``` -------------------------------- ### Applying Fastify Lifecycle Hooks Source: https://context7.com/fastify/fastify-fetch/llms.txt Routes registered with `fastify.fetch.*` are standard Fastify routes. Use `addHook` to apply lifecycle hooks like `onRequest`, `onResponse`, or `onError` before or after route registration. ```javascript const fastify = Fastify({ logger: true }) // Authentication hook — runs before every fetch handler fastify.addHook('onRequest', async (request, reply) => { const token = request.headers.authorization if (!token || !isValidToken(token)) { reply.status(401).send({ error: 'Unauthorized' }) } }) // Timing hook fastify.addHook('onResponse', async (request, reply) => { request.log.info({ url: request.url, ms: reply.elapsedTime }, 'request complete') }) // Error hook fastify.addHook('onError', async (request, reply, error) => { request.log.error({ err: error.message }, 'handler threw an error') }) await fastify.register(fastifyFetch) fastify.fetch.get('/protected', async (request, ctx) => { return Response.json({ data: 'secret content' }) // → 401 if no valid token; → 200 { "data": "secret content" } if authenticated }) ``` -------------------------------- ### Register PUT Route with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a PUT route using fastify.fetch.put for full resource replacement. Handle 404 responses if the resource is not found. ```javascript fastify.fetch.put('/users/:id', async (request, ctx) => { const body = await request.json() // body → { name: 'Alice Updated', email: 'alice@new.com' } const updated = await db.replaceUser(ctx.params.id, body) if (!updated) { return new Response(null, { status: 404 }) } return Response.json(updated) // → 200 { "id": "99", "name": "Alice Updated", "email": "alice@new.com" } ``` -------------------------------- ### Registering fastify-fetch Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Register the fastify-fetch plugin with your Fastify instance. ```APIDOC ## Registering fastify-fetch ```javascript import Fastify from 'fastify' import fastifyFetch from '@fastify/fetch' const fastify = Fastify() await fastify.register(fastifyFetch) // ... your routes await fastify.listen({ port: 3000 }) ``` ``` -------------------------------- ### TypeScript Usage with `@fastify/fetch` Source: https://context7.com/fastify/fastify-fetch/llms.txt Utilize TypeScript by importing and using the exported `FetchHandler`, `FetchContext`, and `FetchRoutes` types for typed handlers and route registration. ```APIDOC ## TypeScript Usage `@fastify/fetch` ships full TypeScript declarations. Use the exported `FetchHandler`, `FetchContext`, and `FetchRoutes` types for typed handlers. ```typescript import Fastify, { FastifyInstance } from 'fastify' import fastifyFetch, { FetchHandler, FetchContext } from '@fastify/fetch' const app: FastifyInstance = Fastify() // Typed standalone handler const getUser: FetchHandler = async (request: Request, ctx: FetchContext): Promise => { const userId = ctx.params.id const user = await fetchUserFromDB(userId) return Response.json(user) } app.register(fastifyFetch).after(() => { // app.fetch is typed as FetchRoutes app.fetch.get('/users/:id', getUser) app.fetch.post('/users', async (request, ctx) => { const body: { name: string; email: string } = await request.json() return Response.json({ created: true, name: body.name }, { status: 201 }) }) }) await app.listen({ port: 3000 }) ``` ``` -------------------------------- ### Using Fastify Lifecycle Hooks Source: https://context7.com/fastify/fastify-fetch/llms.txt Routes registered with `fastify.fetch.*` are standard Fastify routes, allowing the use of Fastify lifecycle hooks like `onRequest`, `onResponse`, and `onError`. ```APIDOC ## Fastify Lifecycle Hooks Routes registered with `fastify.fetch.*` are standard Fastify routes, so all Fastify hooks apply. Use `addHook` on the instance before or after registration. ```javascript const fastify = Fastify({ logger: true }) // Authentication hook — runs before every fetch handler fastify.addHook('onRequest', async (request, reply) => { const token = request.headers.authorization if (!token || !isValidToken(token)) { reply.status(401).send({ error: 'Unauthorized' }) } }) // Timing hook fastify.addHook('onResponse', async (request, reply) => { request.log.info({ url: request.url, ms: reply.elapsedTime }, 'request complete') }) // Error hook fastify.addHook('onError', async (request, reply, error) => { request.log.error({ err: error.message }, 'handler threw an error') }) await fastify.register(fastifyFetch) fastify.fetch.get('/protected', async (request, ctx) => { return Response.json({ data: 'secret content' }) // → 401 if no valid token; → 200 { "data": "secret content" } if authenticated }) ``` ``` -------------------------------- ### Register OPTIONS Route with fastify.fetch.options Source: https://context7.com/fastify/fastify-fetch/llms.txt Use this to register an OPTIONS route, commonly for CORS preflight requests. It returns a 204 No Content response with appropriate CORS headers. ```javascript fastify.fetch.options('/api/*', async (request, ctx) => { return new Response(null, { status: 204, headers: { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS', 'access-control-allow-headers': 'content-type, authorization', 'access-control-max-age': '86400' } }) // → 204 No Content with CORS headers }) ``` -------------------------------- ### fastify.fetch.put(path, handler) Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a PUT route for full resource replacement. ```APIDOC ## `fastify.fetch.put(path, handler)` Register a PUT route for full resource replacement. ```javascript fastify.fetch.put('/users/:id', async (request, ctx) => { const body = await request.json() // body → { name: 'Alice Updated', email: 'alice@new.com' } const updated = await db.replaceUser(ctx.params.id, body) if (!updated) { return new Response(null, { status: 404 }) } return Response.json(updated) // → 200 { "id": "99", "name": "Alice Updated", "email": "alice@new.com" } }) ``` ``` -------------------------------- ### Defining Fetch Handlers Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Define routes using HTTP methods directly on `fastify.fetch`. ```APIDOC ## Defining Fetch Handlers ### Handler Signature ```javascript fastify.fetch.get(path, handler) fastify.fetch.post(path, handler) fastify.fetch.put(path, handler) fastify.fetch.delete(path, handler) fastify.fetch.patch(path, handler) fastify.fetch.options(path, handler) fastify.fetch.head(path, handler) ``` The handler receives two arguments: - `request` - Web Standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object - `ctx` - Context object The handler must return a Web Standard [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object. ``` -------------------------------- ### Registering OPTIONS Routes Source: https://context7.com/fastify/fastify-fetch/llms.txt Register an OPTIONS route, commonly used for CORS preflight responses. The handler should return a Response object. ```APIDOC ## `fastify.fetch.options(path, handler)` Register an OPTIONS route, commonly used for CORS preflight responses. ```javascript fastify.fetch.options('/api/*', async (request, ctx) => { return new Response(null, { status: 204, headers: { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS', 'access-control-allow-headers': 'content-type, authorization', 'access-control-max-age': '86400' } }) // → 204 No Content with CORS headers }) ``` ``` -------------------------------- ### Register POST Route with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a POST route using fastify.fetch.post. Read the request body using request.json(), request.text(), request.formData(), or request.arrayBuffer(). ```javascript fastify.fetch.post('/users', async (request, ctx) => { const body = await request.json() // body → { name: 'Alice', email: 'alice@example.com' } const created = await db.createUser(body) return Response.json({ id: created.id, name: created.name }, { status: 201 }) // → 201 { "id": "99", "name": "Alice" } ``` -------------------------------- ### Fastify Fetch Handler Signatures Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Defines the available HTTP methods for registering fetch handlers. These are standard Fastify routes. ```javascript fastify.fetch.get(path, handler) fastify.fetch.post(path, handler) fastify.fetch.put(path, handler) fastify.fetch.delete(path, handler) fastify.fetch.patch(path, handler) fastify.fetch.options(path, handler) fastify.fetch.head(path, handler) ``` -------------------------------- ### Accessing `ctx.request` and `ctx.reply` Source: https://context7.com/fastify/fastify-fetch/llms.txt When Web Standard APIs are insufficient, access the underlying Fastify `request` and `reply` objects via `ctx.request` and `ctx.reply` for advanced use cases. ```APIDOC ## Accessing `ctx.request` and `ctx.reply` (Fastify Internals) When Web Standard APIs are insufficient, drop down to the underlying Fastify `request` and `reply` objects via `ctx.request` and `ctx.reply`. ```javascript fastify.fetch.get('/multipart', async (request, ctx) => { // Access raw Fastify internals when needed const fastifyReq = ctx.request // FastifyRequest const fastifyRep = ctx.reply // FastifyReply // e.g. read a custom decoration added by another plugin const user = fastifyReq.user // set by an auth plugin // Access the Fastify server instance to use other decorations/plugins const db = ctx.server.db // decorated by a db plugin const records = await db.findByOwner(user.id) return Response.json({ records, owner: user.id }) // → 200 { "records": [...], "owner": "user-123" } }) ``` ``` -------------------------------- ### Using Query Parameters Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Accesses query parameters from the request URL via `ctx.query`. Ensure to parse values as needed, such as converting string limits to integers. ```javascript fastify.fetch.get('/search', async (request, ctx) => { const { q, limit } = ctx.query const results = await search(q, parseInt(limit)) return Response.json(results) }) ``` -------------------------------- ### Register HEAD Route with fastify.fetch.head Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a HEAD route to return only headers and no body. Fastify automatically strips the body from HEAD responses. Useful for returning metadata. ```javascript fastify.fetch.head('/files/:name', async (request, ctx) => { const file = await storage.stat(ctx.params.name) if (!file) { return new Response(null, { status: 404 }) } return new Response(null, { status: 200, headers: { 'content-length': String(file.size), 'last-modified': file.lastModified.toUTCString(), 'etag': file.etag } }) // → 200 with metadata headers, no body }) ``` -------------------------------- ### fastify.fetch.patch(path, handler) Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a PATCH route for partial resource updates. ```APIDOC ## `fastify.fetch.patch(path, handler)` Register a PATCH route for partial resource updates. ```javascript fastify.fetch.patch('/users/:id', async (request, ctx) => { const patch = await request.json() // patch → { email: 'newemail@example.com' } const updated = await db.patchUser(ctx.params.id, patch) return Response.json(updated) // → 200 { "id": "99", "name": "Alice", "email": "newemail@example.com" } }) ``` ``` -------------------------------- ### Reading Request Body Types Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Demonstrates how to read the request body in different formats: JSON, text, FormData, and ArrayBuffer. Use the appropriate method based on the expected content type. ```javascript fastify.fetch.post('/upload', async (request, ctx) => { // JSON const json = await request.json() // Text const text = await request.text() // FormData const formData = await request.formData() // ArrayBuffer const buffer = await request.arrayBuffer() return new Response('OK') }) ``` -------------------------------- ### TypeScript Usage with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Utilize the exported `FetchHandler`, `FetchContext`, and `FetchRoutes` types from `@fastify/fetch` for type-safe handlers and route definitions in TypeScript projects. ```typescript import Fastify, { FastifyInstance } from 'fastify' import fastifyFetch, { FetchHandler, FetchContext } from '@fastify/fetch' const app: FastifyInstance = Fastify() // Typed standalone handler const getUser: FetchHandler = async (request: Request, ctx: FetchContext): Promise => { const userId = ctx.params.id const user = await fetchUserFromDB(userId) return Response.json(user) } app.register(fastifyFetch).after(() => { // app.fetch is typed as FetchRoutes app.fetch.get('/users/:id', getUser) app.fetch.post('/users', async (request, ctx) => { const body: { name: string; email: string } = await request.json() return Response.json({ created: true, name: body.name }, { status: 201 }) }) }) await app.listen({ port: 3000 }) ``` -------------------------------- ### Registering HEAD Routes Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a HEAD route. The handler should return a Response object with headers but no body; Fastify automatically strips the body. ```APIDOC ## `fastify.fetch.head(path, handler)` Register a HEAD route. Return a `Response` with headers but no body; Fastify strips the body automatically. ```javascript fastify.fetch.head('/files/:name', async (request, ctx) => { const file = await storage.stat(ctx.params.name) if (!file) { return new Response(null, { status: 404 }) } return new Response(null, { status: 200, headers: { 'content-length': String(file.size), 'last-modified': file.lastModified.toUTCString(), 'etag': file.etag } }) // → 200 with metadata headers, no body }) ``` ``` -------------------------------- ### fastify.fetch.delete(path, handler) Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a DELETE route. ```APIDOC ## `fastify.fetch.delete(path, handler)` Register a DELETE route. ```javascript fastify.fetch.delete('/users/:id', async (request, ctx) => { const deleted = await db.deleteUser(ctx.params.id) if (!deleted) { return new Response(null, { status: 404 }) } return new Response(null, { status: 204 }) // → 204 No Content }) ``` ``` -------------------------------- ### Register DELETE Route with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a DELETE route using fastify.fetch.delete. Return a 404 status if the resource to be deleted is not found, otherwise return a 204 No Content. ```javascript fastify.fetch.delete('/users/:id', async (request, ctx) => { const deleted = await db.deleteUser(ctx.params.id) if (!deleted) { return new Response(null, { status: 404 }) } return new Response(null, { status: 204 }) // → 204 No Content ``` -------------------------------- ### Context Object Properties Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Details about the properties available in the context object passed to fetch handlers. ```APIDOC ### Context Object | Property | Type | Description | |----------|------|-------------| | `ctx.log` | `FastifyBaseLogger` | Fastify logger instance | | `ctx.server` | `FastifyInstance` | Fastify server instance | | `ctx.params` | `Record` | Route parameters | | `ctx.query` | `Record` | Query string parameters | | `ctx.request` | `FastifyRequest` | Original Fastify request | | `ctx.reply` | `FastifyReply` | Original Fastify reply | ``` -------------------------------- ### Accessing Fastify Internals via ctx.request and ctx.reply Source: https://context7.com/fastify/fastify-fetch/llms.txt When Web Standard APIs are insufficient, access the underlying Fastify `request` and `reply` objects via `ctx.request` and `ctx.reply`. This allows interaction with Fastify decorations and plugins. ```javascript fastify.fetch.get('/multipart', async (request, ctx) => { // Access raw Fastify internals when needed const fastifyReq = ctx.request // FastifyRequest const fastifyRep = ctx.reply // FastifyReply // e.g. read a custom decoration added by another plugin const user = fastifyReq.user // set by an auth plugin // Access the Fastify server instance to use other decorations/plugins const db = ctx.server.db // decorated by a db plugin const records = await db.findByOwner(user.id) return Response.json({ records, owner: user.id }) // → 200 { "records": [...], "owner": "user-123" } }) ``` -------------------------------- ### Register PATCH Route with @fastify/fetch Source: https://context7.com/fastify/fastify-fetch/llms.txt Register a PATCH route using fastify.fetch.patch for partial resource updates. The request body is typically parsed as JSON. ```javascript fastify.fetch.patch('/users/:id', async (request, ctx) => { const patch = await request.json() // patch → { email: 'newemail@example.com' } const updated = await db.patchUser(ctx.params.id, patch) return Response.json(updated) // → 200 { "id": "99", "name": "Alice", "email": "newemail@example.com" } ``` -------------------------------- ### Accessing Request URL Details Source: https://github.com/fastify/fastify-fetch/blob/main/README.md Parses the request URL to extract pathname and search parameters. The `URL` constructor is used for this purpose. ```javascript fastify.fetch.get('/info', async (request, ctx) => { const url = new URL(request.url) return Response.json({ pathname: url.pathname, search: url.search }) }) ``` -------------------------------- ### Access Query String via ctx.query Source: https://context7.com/fastify/fastify-fetch/llms.txt Access parsed query parameters using `ctx.query`, which is a Record. Ensure to parse values like numbers or booleans as needed. ```javascript fastify.fetch.get('/search', async (request, ctx) => { const { q = '', limit = '10', offset = '0' } = ctx.query const results = await db.search({ term: q, limit: parseInt(limit), offset: parseInt(offset) }) return Response.json({ results, meta: { q, limit: parseInt(limit), offset: parseInt(offset), total: results.length } }) // GET /search?q=fastify&limit=5 // → 200 { "results": [...], "meta": { "q": "fastify", "limit": 5, "offset": 0, "total": 3 } } }) ``` -------------------------------- ### Accessing Query String Parameters Source: https://context7.com/fastify/fastify-fetch/llms.txt Access parsed query parameters via `ctx.query`, which is a `Record`. ```APIDOC ## Query String Access via `ctx.query` `ctx.query` is a `Record` containing all parsed query parameters. ```javascript fastify.fetch.get('/search', async (request, ctx) => { const { q = '', limit = '10', offset = '0' } = ctx.query const results = await db.search({ term: q, limit: parseInt(limit), offset: parseInt(offset) }) return Response.json({ results, meta: { q, limit: parseInt(limit), offset: parseInt(offset), total: results.length } }) // GET /search?q=fastify&limit=5 // → 200 { "results": [...], "meta": { "q": "fastify", "limit": 5, "offset": 0, "total": 3 } } }) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.