Next.js Discord

Discord Forum

Debugging API requests that are sent from request handlers

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Hey, I've created myself a request handler that makes simple API call to my own API using the fetch wrapper. However my call is failing, yet I have not figured out a way to debug this properly.

Is there a way I could observe the outbound request for the request that I send from the route handler. I would like to see what headers does it have attached and whatnot.

Here's my code:

import { cookies } from 'next/headers';
import { NextRequest } from "next/server";

export async function GET(req: NextRequest) {
    const cookieStore = cookies();
    const authToken = cookieStore.get('auth.access-token');

    const authRequest = fetch(`${process.env.API_ROOT}/api/v2/auth/check`, {
        headers: {
            'Authorization': 'Bearer ' + authToken,
        },
        cache: 'no-store'
    });

    return await authRequest
}


In this case the authRequest is the outbound request I would like to inspect.

8 Replies

You can debug your variables by using console.log("your message"). You can also enter not only messages, also variables. So add a few console.log messages for the variables that you want to see and they will be printend into your log ^^
@Asian black bear
Asian black bearOP
If I log the authRequest as per the code, it is just a pending promise, that does not give me access to for example the body of the outbound request or headers, at least that I'm aware of 🤔
And to add, the promise will resolve to the response of the request, but I would need to debug and inspect the outbound request as I would with browser network tab for example, to make sure my headers are configured correctly.
Asian black bearOP
Right, but that will only allow me to access the response headers, not the actual request headers that I'm sending to the API, therefore I can only observe what comes back for the request but not the request itself
ah ok. You can check them by building a new request like this:
const requestInit = {
        headers: {
            'Authorization': 'Bearer ' + authToken,
        },
        cache: 'no-store'
    };

    const outboundRequest = new Request(`${process.env.API_ROOT}/api/v2/auth/check`, requestInit);

    console.log('Outbound Request URL:', outboundRequest.url);
    console.log('Outbound Request Headers:', outboundRequest.headers);

    const authRequest = fetch(outboundRequest);

    const response = await authRequest;
    console.log('Response Headers:', response.headers);
Asian black bearOP
But there is no way to intercept the actual request? I would have to just trust that fetch is submitting all the data I give to it?