JongminLee93 / myStudy

프로그래밍 전반에 대한 공부를 기록하기 위한 레파지토리입니다.
0 stars 0 forks source link

[Nextjs, HTTP] request 차이 #3

Open JongminLee93 opened 8 months ago

JongminLee93 commented 8 months ago

배경

Next js에서 Strapi API로 request를 보내는 과정에서 Authorization 헤더를 추가해야 함. Next auth 를 사용해서 토큰을 불러와 header에 추가하는 과정에서 다음과 같은 코드를 작성

import { getToken } from 'next-auth/jwt';
import { NextRequest } from 'next/server';

const handler = async (req: NextRequest) => {
  // fetch confirm
  console.log('next API for strapi API')

  // fetch url
  const { pathname, searchParams } = req.nextUrl;

  const path = pathname.replace('/nextapi/strapi', '');
  const queryString = searchParams.toString();

  const url = `http://seaq-strapi:1337/api${path}${queryString ? `?${queryString}` : ""}`;

  // fetch options
  const { method, headers } = req;

  const token = await getToken({ req });
  if (!token) throw new Error("The Keycloak access token is not set.");

  const accessToken = token.access_token;

  const contentType = headers.get('Content-Type');

  const body = contentType?.includes('multipart/form-data')? await req.formData() :
               contentType?.includes('application/json')? await req.json() : req.body

  const options = {
    method,
    next: { revalidate: 60 },
    headers: {
      Authorization: `Bearer ${accessToken}`,
      ...headers
    },
    body
  }

  return await fetch(url, options);
}

export { handler as DELETE, handler as GET, handler as POST, handler as PUT };

이 코드는 다음과 같이 작성 가능

import { getToken } from 'next-auth/jwt';
import { NextRequest } from 'next/server';

const handler = async (req: NextRequest) => {
  // fetch confirm
  console.log('next API for strapi API')

  // fetch url
  const { pathname, searchParams } = req.nextUrl;

  const path = pathname.replace('/strapi/auth', '');
  const queryString = searchParams.toString();

  const url = `http://seaq-strapi:1337/api${path}${queryString ? `?${queryString}` : ""}`;

  // fetch options
  const { method, headers, body } = req;

  const token = await getToken({ req });
  if (!token) throw new Error("The Keycloak access token is not set.");

  const accessToken = token.access_token;

  headers.append('Authorization', `Bearer ${accessToken}`);

  const options = {
    method,
    next: { revalidate: 60 },
    headers,
    body
  }

  return await fetch(url, options);
}

export { handler as DELETE, handler as GET, handler as POST, handler as PUT };

두 코드의 차이는?