본문 바로가기
매일 해내는 개발/Develog

[Develog] 자바스크립트에서 SSR 구현하는 방법

by 해야지 2023. 3. 16.
반응형

SSR(Server-Side Rendering)은 서버에서 HTML, CSS, JavaScript 등을 렌더링하여 클라이언트에게 전달하는 방식이다. 

1. Node.js 설치
Node.js는 JavaScript를 실행할 수 있는 서버 측 런타임으로 SSR을 구현하려면 필요하다.
공식 홍페이지(https://nodejs.org/)에서 다운로드하거나, 패키지 매니저를 통해 설치할 수 있다.

2. 프로젝트 생성
SSR을 구현할 프로젝트를 생성해야한다. 프로젝트 생성 방법은 아래와 같다.

mkdir my-ssr-project
cd my-ssr-project
npm init -y

이 명령어를 실행하면 `package.json`파일이 생성된다.

3. 서버 환경 구성
Express.js는 Node.js를 기반으로 동작하는 웹 프레임워크이다. Node.js와 Express.js를 사용하여 서버 환경을 구성한다. 필요한 라이브러리를 설치하고, Express.js 앱을 생성한다.

npm install express react react-dom react-router-dom
// server.js

const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');

const App = require('./App').default; // 클라이언트 앱

const app = express();

app.use(express.static('public'));

app.get('*', (req, res) => {
  const context = {};
  const html = ReactDOMServer.renderToString(
    <StaticRouter location={req.url} context={context}>
      <App />
    </StaticRouter>
  );

  res.send(`
    <html>
      <head>
        <title>My App</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <script src="bundle.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

4. 클라이언트 앱 구현
React 앱을 만든다. 이 앱은 서버에서 렌더링할 때와 클라이언트에서 렌더링할 때 모두 사용된다.

// App.js

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
  return (
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </Switch>
  );
}

export default App;

 

5. 클라이언트 앱 빌드
Webpack을 사용하여 클라이언트 앱을 빌드한다. 이때 서버에서 렌더링할 때 필요한 파일을 생성해야 한다.

// webpack.config.js

const path = require('path');

module.exports = {
  entry: './client.js',
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react'],
          },
        },
      },
    ],
  },
};

 

6. 서버 실행

node server.js

 

이제 브라우저에서 http://localhost:3000에 접속하여 앱이 정상적으로 동작하는지 확인할 수 있다.

반응형

댓글