[Nextjs] 정적배포시 다른 서버를 둔다면?

Jsleemaster·2023년 4월 28일
1

Next.js

목록 보기
1/1
post-thumbnail

현재 상황은
프론트는 Nextjs로 구성하고 백엔드는 Koa로 구성했는데
문제는 정적배포시 next.config.js에 rewrites는 사라진다는 점이다.

그래서 아래와 같이 axios 통신하는 단에서 직접 붙혀넣고 백엔드 cors를 설정하여 해결하였다.

// next.config.js
/** @type {import('next').NextConfig} */
const env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';
const config = {
  dev: {
    host: `http://localhost:22222`,
  },
  prod: {
    host: `배포시 호스트명`,
  },
}
const nextConfig = {
  env: {
    customHost: config[env].host,
  },
  ...
}

module.exports = nextConfig
//axios.js
import axios from "axios";
const host = process.env.customHost;
axios.get(host + url, ...);
...

백엔드 쪽에선 cors오류가 나와서
@koa-cors를 이용했고
아래와 같이 동적으로 도메인을 허용해주었다


// 허용되는 도메인설정
const domain = [
  "http://localhost:3000", // 로컬
  "도메인1",
  "도메인2"
]

router
  .use(cors({
    origin: function (ctx) {
      const allowedOrigins = domain;
      const origin = ctx.request.headers.origin;
      if (allowedOrigins.includes(origin)) {
        return origin;
      } else {
        return false;
      }
    },
    credentials: true
  }))

뭔가 찝찝하지만 잘못된 점이 있으면 알려주시면 감사합니다..

profile
문제 기록 블로그

0개의 댓글