Redux Toolkit을 활용한 자바스크립트 서버 사이드 렌더링

서버 사이드 렌더링 (Server Side Rendering, SSR)은 사용자에게 초기 페이지 로딩 속도를 향상시켜 주는 방법 중 하나입니다. 이를 통해 웹 애플리케이션의 첫 화면을 더 빠르게 랜더링 할 수 있습니다.

Redux Toolkit은 Redux 애플리케이션을 더욱 효율적으로 개발할 수 있도록 도와주는 강력한 도구입니다. Redux Toolkit은 반복적인 작업을 자동화하고, 상태 관리를 단순화하기 위한 여러 유틸리티 기능을 제공합니다. 이러한 도구를 활용하여 SSR에 Redux를 통합하는 방법을 알아보겠습니다.

1. Redux 초기 설정

먼저, Redux Toolkit을 위한 초기 설정을 해야 합니다. 다음과 같은 패키지를 설치합니다.

npm install react-redux redux redux-thunk redux-promise-middleware

Redux Toolkit을 사용하기 위해 configureStore 함수를 사용하여 store를 생성합니다.

// store.js
import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer: {
    // reducers
  },
});

export default store;

2. 서버 사이드 렌더링을 위한 설정

서버 사이드 렌더링을 구현하기 위해 Express.js를 사용하겠습니다. 먼저, Express.js 설정을 위해 다음 패키지를 설치합니다.

npm install express express-http-proxy

서버 사이드 렌더링을 위한 핵심 로직을 구현합니다.

// server.js
import 'babel-polyfill';
import path from 'path';
import express from 'express';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
import App from './components/App';

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.static(path.resolve(__dirname, 'public')));
app.use('/api', proxy({ target: 'http://api.example.com', changeOrigin: true }));

app.get('*', (req, res) => {
  const store = createStore(reducers, {}, applyMiddleware(thunk));
  
  const context = {};
  const app = (
    <Provider store={store}>
      <StaticRouter location={req.url} context={context}>
        <App />
      </StaticRouter>
    </Provider>
  );

  const content = renderToString(app);
  
  if (context.url) {
    res.redirect(context.url);
  } else {
    res.send(`
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>React SSR</title>
        </head>
        <body>
          <div id="root">${content}</div>
          <script src="/bundle.js"></script>
        </body>
      </html>
    `);
  }
});

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

3. Redux 상태 초기화

서버 사이드 렌더링 시, 서버와 클라이언트 간에 Redux 상태가 동기화되지 않을 수 있습니다. 이를 해결하기 위해, 서버에서 초기 상태를 생성하여 클라이언트로 전달해야 합니다.

// server.js
// ...

app.get('*', (req, res) => {
  const store = createStore(reducers, {}, applyMiddleware(thunk));
  
  // 비동기 작업 수행 후 상태 변경
  await store.dispatch(fetchData());
  
  const initialState = store.getState();
  
  // ...
});

// ...

마무리

Redux Toolkit을 활용한 자바스크립트 서버 사이드 렌더링은 초기 로딩 속도를 향상시키는 좋은 방법입니다. Redux Toolkit의 강력한 기능을 활용하여 Redux 상태를 쉽게 관리하고 서버 사이드 렌더링을 구현할 수 있습니다.

#javascript #redux #ssr