공부한거 정리하는 노트에요

Next.js Socket Hangup 오류

by 구설구설

발생한 문제

백엔드에서 구현한 API를 이용해 위성 영상 파일을 업로드하는 기능을 개발 중, 다음과 같은 문제가 발생했다.

  • 작은 파일 업로드: 정상 작동
  • 큰 파일(1GB 이상) 또는 여러 파일 업로드: 백엔드에서 응답을 보내지 않았으나 500 Internal Error 발생, 콘솔에는 아래와 같은 오류 출력:
Failed to proxy {백엔드 API 주소} Error: socket hang up
    at Socket.socketCloseListener (node:_http_client:479:27)
    at Socket.emit (node:events:532:35)
    at TCP.<anonymous> (node:net:337:12)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  code: 'ECONNRESET'
}
Error: socket hang up
    at Socket.socketCloseListener (node:_http_client:479:27)
    at Socket.emit (node:events:532:35)
    at TCP.<anonymous> (node:net:337:12)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  code: 'ECONNRESET'
}

 

 

해결 시도

Axios Timeout 설정

프로젝트에서 axios를 사용해 백엔드 API에 요청을 보내고 있었기에, 문제 원인이 ~axios timeout~일 것이라 판단했다.

하지만, axios의 timeout 값을 조정해도 동일한 socket hang up 오류가 발생했다.

이후 찾아보니 axios는 기본적으로 timeout 설정을 하지 않으면 응답이 올 때까지 대기한다는 것을 알게 되었다.

 

문제의 원인

문제의 원인은 Next.js의 ~rewrite~ 기능이었다.

프론트엔드에서 백엔드로 요청을 보낼 때 API 주소를 숨기기 위해 rewrite()를 사용하고 있었는데, 이 기능은 기본적으로 proxy timeout을 30초로 제한한다.

요청 시간이 30초를 초과하면서 socket hang up 오류가 발생했던 것이다.

자세한 정보는 아래 링크에서 확인할 수 있다.

 

nextJs proxy timeout after 5 seconds

My front-end is in react.ts(nextJs version - 13.4.9) and the backend spring boot. One of our clients makes an API call to the front-end and the front-end passes the the request to the backend using

stackoverflow.com

 

현재 사용 중인 Next.js 버전(14.2.13)의 타임아웃 관련 코드는 아래와 같다.

// Next.js 14.2.13 버전의 timeout 코드
async function proxyRequest(req, res, parsedUrl, upgradeHead, reqBody, proxyTimeout) {
    const { query } = parsedUrl;
    delete parsedUrl.query;
    parsedUrl.search = (0, _serverrouteutils.stringifyQuery)(req, query);
    const target = _url.default.format(parsedUrl);
    const HttpProxy = require("next/dist/compiled/http-proxy");
    const proxy = new HttpProxy({
        target,
        changeOrigin: true,
        ignorePath: true,
        ws: true,
        // we limit proxy requests to 30s by default, in development
        // we don't time out WebSocket requests to allow proxying
        proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30000,
        headers: {
            "x-forwarded-host": req.headers.host || ""
        }
    });

 

 

해결 방법

다행히, Next.js에서는 ~next.config.mjs~ 파일에 ~experimental.proxyTimeout~ 옵션을 추가하여 timeout 값을 조정할 수 있었다.

const nextConfig = {  
  experimental: {
    proxyTimeout: 10 * 60 * 1000, // 10분으로 설정
  },
};

이 설정을 적용한 뒤, 빌드 시 실험 기능 사용 경고가 뜨기는 하지만 문제가 해결되었다.

 

 

정리

  1. 문제: 큰 파일(1GB 이상) 또는 다중 파일 업로드 시 rewrite로 인해 30초 제한이 발생하며 socket hang up 오류가 발생.
  2. 원인: Next.js에서 기본적으로 설정된 proxyTimeout이 30초로 제한되어 있음.
  3. 해결 방법: next.config.mjs 파일에 experimental.proxyTimeout 옵션을 사용해 timeout 값을 10분으로 연장.

블로그의 정보

공부중임

구설구설

활동하기