Next.js Discord

Discord Forum

Is there any way to add a header right before you make a request with graphql-request at the API lev

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
I have setup NextAuth and want to know if there's any way to set the authorization header at the API route for all the different API routes I have so I don't have to repeat getToken from next-auth on every single one of the request that look something like the following:

import request from 'graphql-request';
import type { NextApiRequest, NextApiResponse } from 'next';
import { Document } from '../../graphql/generated';


export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const apiUrl = process.env.API_URL || "";

  const data = await request({
    url: apiUrl,
    document: Document,
    variables: {
      input
    },
  });

  return res.status(200).json(data);
}


Something like using middleware but for the last part of the request

Or since I'm using graphql-request it's something I have to absolutely do there?

4 Replies

 const data = await request({
    url: apiUrl,
    document: Document,
    variables: {
      input
    },
    requestHeaders: {
      "Authorization": "token"
    }
  });

like this?
Cape lionOP
hi! not really, I have like 40-50 api routes at the moment and wanted to add that header to that request to my external GQL api and attach the authorization header
like this
export async function createGraphqlClient(req: NextApiRequest) {
  const token = await getToken({req})
  if (!token) {
     throw new Error("not authorize")
  }
  const apiUrl = process.env.API_URL || "";
  return new GraphQLClient(apiUrl, {
    headers: {
      authorization: `Bearer ${token}`,
    },
  })
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
  const client = await createGraphqlClient(req)
  const data = await client.request({
    document: Document,
    variables: {
      input
    },
  });

  return res.status(200).json(data);
  } catch (e) {
    return res.status(401).end()
  }
}