Reading the body of a request in hooks.server in sveltekit
Asked Answered
D

2

12

I want to read the body of a request in my hooks.server.ts import type { Handle } from '@sveltejs/kit';

export const handle = (async ({ event, resolve }) => {
  console.log(event.request.body);
 
  const response = await resolve(event);
  return response;
}) satisfies Handle;

This gives me

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

If i read it

const reader = request.body.getReader();
let text;
let result;
while (!(result = await reader.read()).done) {
   text += result.value;
}
console.log(text);
console.log(request.body);

And then log the body, i get:

ReadableStream { locked: true, state: 'closed', supportsBYOB: false }

This leads to the actuall call I want to do to thrown an error

TypeError: Body is unusable at specConsumeBody (/home/hp/git/booking/node_modules/undici/lib/fetch/body.js:492:11) at Request.json (/home/hp/git/booking/node_modules/undici/lib/fetch/body.js:359:14)

How can I read the body in hooks?

Dulcie answered 10/1, 2023 at 14:22 Comment(0)
M
9

You can clone() the Request and work with that to not modify the original.

Merengue answered 10/1, 2023 at 14:25 Comment(0)
N
24

I got the error TypeError: Body is unusable when trying to debug a POST request with a JSON body because I did await the request twice.

console.log(await request.text()) // X only this is logged
console.log(await request.json()) // --> throws error

Instead, only await the request once!

console.log(await request.json()) // logs, no error
Navel answered 18/3, 2023 at 13:56 Comment(0)
M
9

You can clone() the Request and work with that to not modify the original.

Merengue answered 10/1, 2023 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.