쿠키 전송- server api, client api

|

내가 작성한 코드였는데도, 쿠키 관련 개념을 자꾸 헷갈려서 정리함.

회사 프로젝트를 진행하면서 fetch를 server 환경과 client 환경에 맞게 분리해줬었다.
이렇게 나눈 가장 큰 이유는 바로 쿠키(Cookie) 때문이었다.


핵심 개념

Client API (브라우저 환경)

브라우저에서는 쿠키가 자동으로 포함된다.
즉, axios나 fetch 요청 시 withCredentials: true 옵션만 주면 브라우저가 알아서 쿠키를 첨부한다.
헤더에 직접 쿠키를 넣을 필요가 없다.

Server API (Node.js 환경)

반면, 서버에서 실행되는 코드(Next.js server actions, getServerSideProps, route handlers 등)는 브라우저 환경이 아니기 때문에 쿠키를 자동으로 포함하지 않는다.
따라서 직접 쿠키를 읽어서 헤더에 실어줘야 한다.


Server API 예시

import { cookies } from 'next/headers';
import axios from 'axios';

export async function serverApi(endpoint) {
  const cookieStore = cookies();

  const res = await axios.get(
    `${process.env.NEXT_PUBLIC_BACKEND_URL}${endpoint}`,
    {
      headers: {
        Cookie: cookieStore.toString(), // 🍪 직접 쿠키 전달
      },
    }
  );

  return res.data;
}

Client API 예시

import axios from 'axios';

axios.get('/api/current-user', {
  withCredentials: true, // ✅ 브라우저가 자동으로 쿠키를 첨부
});