NEXT JS 13 url의 params를 통한 fetch했을 때의 Error

김삿갓의싱잉랩·2023년 10월 11일
0

👀 문제 상황

지금 next js 13버전 app-routing 방식을 사용해서 공부중이었다.
엔드포인트에 특정한 파라미터를 주어야 해서

const fetchKV = async (name: string) => {
	const param1 = name;
	const res = await fetch(`/api/cart?param1=${param1}`, {
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
		},
	});

	if (!res.ok) {
		throw new Error(res.statusText);
	}

	return res.json();
};

다음과 같이 코드를 작성하였다.
허나 Faild to parse URL 이라는 에러가 발생했다.

✅ 해결 과정

'use client'를 사용했을 때는 분명 작동하던 코드가 server client로 변경되면 작동이 되지 않았다.

그 이유를 찾아본 결과 서버 컴포넌트가 서버에서 작동하기 때문에 그렇다고 한다.
당연한 말이겠지만 서버에서 작동하기 때문에 절대적인 URL의 paths가 필요하다.

그렇기 때문에

const fetchKV = async (name: string) => {
	const param1 = name;
	const res = await fetch(`http://localhost:3000/api/cart?param1=${param1}`, {
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
		},
	});

	if (!res.ok) {
		throw new Error(res.statusText);
	}

	return res.json();
};

server component에서 data를 url의 params를 통해서 fetching하려면 절대적인 경로를 적어주어야 한다.

이제 잘 작동하는 것을 볼 수 있다.
허나 이러면 개발할 때와 배포할 때 유동적으로 변경할 수 없다는 단점이 있다.
이를 해결하기 위해 다음과 같은 방법으로 변경하였다.

const fetchKV = async (name: string) => {
	const param1 = name;
	const host = headers().get('host');
	const protocol = process?.env.NODE_ENV === 'production' ? 'https' : 'http';
	const res = await fetch(`${protocol}://${host}/api/cart?param1=${param1}`, {
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
		},
	});

	if (!res.ok) {
		throw new Error(res.statusText);
	}

	return res.json();
};

잘 작동한다 😊

✅ 느낀점

server component와 client component에 대한 이해를 더 많이 필요로 한다는 것을 느낄 수 있었다. 그래도 fetching할 수 있는 좋은 방법을 알 수 있어서 이제 유동적으로 활용할 수 있을 것 같다.

profile
시스템 개발에 시간을 아끼지 말자

1개의 댓글

comment-user-thumbnail
2024년 4월 27일

이 글이 5시간 동안 환경변수와 싸우던 저를 구원했습니다...감사합니다....

답글 달기