ETC -

Next JS에서 Node.js API 사용

  • -

안녕하세요 TripexLab 입니다.
오늘은 Next JS에서 Node의 API를 사용하는 방법에 대해서 살펴보겠습니다.

NextJS는 React 기반(문법)의 프레임워크로 유명합니다.
React기반의 함수형 컴포넌트를 사용해서 웹앱서비스를 만들수 있죠. 그리고 NextJS는 app 폴더 하위에 있는 모든 컴포넌트들은 기본적으로 서버컴포넌트 이므로(서버에서 동작함) 서버에 있는 파일을 읽고, 쓰고를 할수 있고 서버에 있는 경로도 접근이 가능합니다.

👉🏻NextJS 컴포넌트는 기본적으로 서버 사이드 렌더링(SSR) 합니다.

예를들어서 다음과 같이 비즈니스 로직을 보면 "path"와 "fs/promises"에 접근해서 가져올수가 있습니다.

// src/service/posts.ts
import { readFile } from "fs/promises";
import path from "path";

export type Post = {
  title: string;
  description: string;
  date: Date;
  category: string;
  path: string;
  featured: boolean;
};

export async function getAllPosts(): Promise<Post[]> {
  const filePath = path.join(process.cwd(), 'data', 'posts.json');
  return readFile(filePath, 'utf-8')
  .then<Post[]>(JSON.parse)
  .then(posts => posts.sort((a, b) => (a.date > b.date ? -1 : 1)))
};

export async function getFeaturedPosts(): Promise<Post[]> {
  return getAllPosts().then(posts => posts.filter(post => post.featured));
};

export async function getNonFeaturedPosts(): Promise<Post[]> {
  return getAllPosts().then(posts => posts.filter(post => !post.featured));
};

그리고 getFeaturedPosts함수를 호출해서 데이터를 받는 것을 콘솔을 찍어보면 터미널에서 값을 확인할수가 있습니다.

// src/components/FeaturedPosts.tsx

import { getFeaturedPosts } from "@/service/posts";
import PostsGrid from "./PostsGrid";

export default async function FeaturedPosts() {
  const posts = await getFeaturedPosts();
  console.log(posts);
  
  return (
    <section className="my-4">
      <h2 className="text-2xl font-bold my-2">Featured Posts</h2>
      <PostsGrid posts={posts} />
    </section>
  );
};

터미널에서 콜솔값을 확인한 모습

터미널에서 콘솔값을 확인 할수 있다라는것 자체가 NextJS 컴포넌트는 기본적으로 서버 사이드 렌더링(SSR)을 하고 있다는 증거입니다.
클라이언트 사이드 렌더링(CSR)이였다면 브라우저 콘솔창으로 값을 확인해야 할텐데 말이죠.
여기까지 알아보면서 정말 신기했습니다.

👉🏻특정 컴포넌트 클라이언트 사이드 렌더링(CSR)로 변경

그리고 특정 컴포넌트나, 페이지를 클라이언트 사이드 렌더링(CSR)로 변경할수도 있는데요
바로 'use client'를 상단에 작성하면 특정 컴포넌트는 클라이언트 사이드 렌더링(CSR)으로 렌더링 됩니다.

'use client'
import React from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

type Props = {
  children: React.ReactNode;
}

export default function MultiSwiper({children}: Props) {
  console.log(children)

  return (
    <Swiper 
    slidesPerView={3}
    spaceBetween={30}
    pagination={{
      clickable:true
    }}
    modules={[Pagination]}
    breakpoints={{
      320: {
        slidesPerView: 1,
        spaceBetween: 30,
      },
      640: {
        slidesPerView: 1,
        spaceBetween: 10,
      },
      768: {
        slidesPerView: 2,
        spaceBetween: 20,
      },
      1024: {
        slidesPerView: 3,
        spaceBetween: 30,
      },
    }}
    className="mySwiper">
      {React.Children.map(children, (child) => (
        <SwiperSlide>{child}</SwiperSlide>
      ))}
    </Swiper>
  );
}

브라우저 콘솔에서 children값을 확인 할수가 있습니다. 

브라우저 콘솔창으로 값을 확인

👉🏻정리

이렇게 NextJS에서 SSR과 CSR의 차이점과 방법에 대해서 살펴봤습니다.
공부를 하다보니 신기했고, 개발자가 상황에 따라서 렌더링 방식을 변경할수 있다는것 자체도 신기했습니다.
그래서 풀 스택 개발자도 가능하다 였네요. 소문으로만 듣었는데 실제로 체험 해보니깐 확 와닿네요ㅎㅎ

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.