๐ŸŽ‡ Next.js ๋ฏธ๋“ค์›จ์–ด ์„ค์ •ํ•˜๊ธฐ

@JavaPark ยท September 14, 2023 ยท 2 min read

next.js์—์„œ ๋ฏธ๋“ค์›จ์–ด ์‚ฌ์šฉํ•˜๊ธฐ

Next.js์—์„œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด next.config.js ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๊ณ  next.config.js ํŒŒ์ผ์—์„œ middleware๋ฅผ ์„ค์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋ฏธ๋“ค์›จ์–ด๋Š” ํŽ˜์ด์ง€์˜ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์ „์— ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜๋กœ, ์š”์ฒญ์„ ๊ฐ€๋กœ์ฑ„๊ณ  ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

๋‹ค์Œ์€ Next.js์—์„œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค:

  1. next.config.js ํŒŒ์ผ ์ƒ์„ฑ: ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ ๋””๋ ‰ํ† ๋ฆฌ์— next.config.js ํŒŒ์ผ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
  2. ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜ ์ž‘์„ฑ: ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋Š” ์š”์ฒญ(request), ์‘๋‹ต(response), ๊ทธ๋ฆฌ๊ณ  next() ํ•จ์ˆ˜๋ฅผ ์ธ์ž๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๊ฐ„๋‹จํ•œ ๋กœ๊น… ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์ž‘์„ฑํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
// middleware/logger.js

export default function logger(req, res, next) {
  console.log(`Request received for: ${req.url}`);
  next(); // ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด๋‚˜ ํ•ธ๋“ค๋Ÿฌ๋กœ ์š”์ฒญ์„ ์ „๋‹ฌ
}
  1. next.config.js์—์„œ ๋ฏธ๋“ค์›จ์–ด ์„ค์ •: `next.config.js ํŒŒ์ผ์—์„œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์ ์šฉํ•  ํŽ˜์ด์ง€๋‚˜ API ๊ฒฝ๋กœ๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
// next.config.js

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: '/api-handler/:path*',
      },
    ];
  },
  async redirects() {
    return [
      {
        source: '/old-route',
        destination: '/new-route',
        permanent: true,
      },
    ];
  },
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: securityHeaders,
      },
    ];
  },
  async middleware() {
    return [
      '~/middleware/logger.js', // ๋ฏธ๋“ค์›จ์–ด ํŒŒ์ผ์˜ ์ƒ๋Œ€ ๊ฒฝ๋กœ๋‚˜ ๋ชจ๋“ˆ ๊ฒฝ๋กœ๋ฅผ ์ง€์ •
    ];
  },
};

์œ„ ์˜ˆ์ œ์—์„œ๋Š” logger.js ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์„ค์ •์— ์ถ”๊ฐ€ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ, rewrites, redirects, headers ์„น์…˜์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ๋ผ์ดํŠธ, ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ, ํ—ค๋”๋ฅผ ์กฐ์ž‘ํ•˜๋Š” ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์„ค์ •ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด์ œ Next.js ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ํŠน์ • ํŽ˜์ด์ง€๋‚˜ API ๊ฒฝ๋กœ์—๋งŒ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์ ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด, next.config.js์—์„œ ํ•ด๋‹น ๊ฒฝ๋กœ์— ๋Œ€ํ•œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

@JavaPark
Welcome to Javapark blog!!