본문 바로가기

개발 방법론

SSR Frameworks

왜 SSR을 선택할까?

  CSR SSR
데이터 로드 측면 초기 로딩은 느리지만 한번 로드된 이후에는 필요한 부분만 갱신하기 때문에 부드러운 전환, 빠른 페이지 전환이 가능함 (SPA) 서버에서 렌더링이 된 HTML소스를 그대로 보여주기 때문에 초기로딩이 빠름.
렌더링 책임 (서버 부하) 프론트엔드 렌더링이 프론트엔드에서 이루어지므로 서버부하가 상대적으로 낮을 수 있음 백엔드 서버에서 모두 렌더링이 이루어지므로 서버 부하가 높아질 수 있음 TTFB 증가: 서버에서 렌더링 작업을 완료해야 데이터 전송이 가능함
기기 성능 요구 상대적으로 높음.

클라이언트 렌더링으로 인한 성능이 어느정도 뒷받침이 되어야 하지만 최근 기기의 스펙으로는 threejs같은 아주 큰 렌더링 스펙을 요구하는 상황이 아니라면 정상적으로 로딩가능할 것으로 보임
낮음
SEO 동적인 contents load로 인해 검색 엔진 crawler가 제대로 가져가지 못할 수 있음

"SEO 인덱싱에 불리하다"
서버에서 렌더링이 된 정적인 contents load로 인해 crawler가 제대로 가져갈 수 있음

”SEO 친화적이다”
임베딩 공유 SEO 특성과 비슷한 측면임. 외부에 공유했을 때 SEO와 같은 이유로 미리보기가 안보일 수 있음 SEO 특성과 비슷한 측면임. 외부에 공유했을 때 SEO와 같은 이유로 미리보기가 잘 보임
작업 특성 데이터만을 주고받음으로써 frontend에서 독립적으로 비동기적으로 자유롭게 작업이 구성가능하다. 동적인 UI 표현이 상대적으로 자유롭다. (예를 들면 스크롤에 따라 동적으로 내용 lazy load, … 등등) 최근 프레임워크의 다양한 기능지원으로 인해 왠만한 동적 로드도 가능은 하지만 상대적으로 불리함. 어차피 이러한 동적로드 구현할 상황일 경우 SSR 프로젝트에서도 CSR과 비슷하게 구현해야 함
작업 영역 분리 프론트엔드와 백엔드의 분리가 확실함 프론트와 백엔드 사이의 분리가 흐릿함. 이에 인하여 개발복잡성이 증가함
  • TTFB(Time To First Byte) : 웹서버에 리소스를 요청한 시점부터 서버로부터 첫번째 바이트의 데이터를 받기 시작하는 시점까지의 시간

NextJS

개요

파일구조가 url을 따라가는 구조로 주로 구성함

참고 url

Docs

Introduction

etc

SSR 서버 최적화로 비용 아끼기

01) Next.js 프로젝트 설정

예시코드

설치

npx create-next-app@latest

코드

import { notFound } from 'next/navigation'

// 정적 페이지 생성을 위한 함수
export async function generateStaticParams() {
  const posts = await fetchPosts() // 외부 데이터 소스에서 게시물 가져오기

  return posts.map((post) => ({
    slug: post.slug,
  }))
}

async function getPost(slug) {
  // 실제 프로젝트에서는 DB나 CMS에서 데이터 가져오기
  const posts = {
    'first-post': {
      title: '첫 번째 게시물',
      content: '첫 번째 게시물의 내용입니다.',
    },
    'second-post': {
      title: '두 번째 게시물',
      content: '두 번째 게시물의 내용입니다.',
    },
  }

  return posts[slug]
}

export default async function BlogPost({ params }) {
  const post = await getPost(params.slug)

  if (!post) {
    notFound()
  }

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </article>
  )
}

Remix

개요

기본적으로 remix와 비슷함. React 기반임

remix 3 버전부터 react-router 7버전의 framework 모드로 통합되버림으로써 유명해짐. 최근에 가장 주목받고 있는 JS SSR framework 임.

표준 web api를 사용하여 web platform 위에 remix framework가 구축되어 있어 빌드 환경이 NextJS에 비해 자유로움.

프로젝트 폴더구조가 그대로 url path로 따라감

참고 url

Docs

Quick Start (5m) | Remix

etc

https://www.youtube.com/watch?v=5r44Te7V5RI

예시코드

설치

npx create-remix@latest my-remix-app
cd my-remix-app
npm run dev

파일구조

. (File Root Directory)

  • app/
    • entity.client.jsx
    • entity.server.jsx
    • root.jsx
    • routes/ # 라우트
      • _index.jsx # /
      • about.jsx # /about
      • blog/
        • _index.jsx # /blog
        • $slug.jsx # /blog/:slug
    • styles/
    • models/
  • public/
  • remix.config.js

코드

export default function Index() {
  return (
    <div>
      <h1>Remix 애플리케이션에 오신 것을 환영합니다!</h1>
    </div>
  );
}
import { Link } from "react-router"; 

export async function loader() {
  const product = await db.query.posts.findMany();
  return {
    product
  };
}
import { useLoaderData } from "@remix-run/react";

export async function loader({ params }) {
  const product = await getProduct(params.productId);
  return { product };
}

export default function ProductRoute() {
  const { product } = useLoaderData();
  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <span>{product.price}원</span>
    </div>
  );
}

NestJS - hbs (MVC Pattern)

개요

NestJS는 기본적으로 CSR를 사용하지만 handlebars를 사용한 방식도 많이 사용한다.

참고 url

Docs

Documentation | NestJS - A progressive Node.js framework

예시코드

설치

npm i -g @nestjs/cli
nest new project
npm install --save hbs

파일 구조

. (File Root Directory)

  • src
    • controllers
      • app.controller.ts
    • modules
      • app.modules.ts
    • main.ts

코드

  • main.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './modeuls/app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
  );

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

 

  • app.controller.ts
import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}
  • index.hbs
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>App</title>
  </head>
  <body>
    {{ message }}
  </body>
</html>

그 외 인기 SSR Frameworks

  • NuxtJS
    Vue 기반 SSR framework
  • SvelteKit
    Svelte 기반 SSR framework

추이

npm trends

next vs react vs remix | npm trends

github stars

GitHub Star History

반응형