SENTENCE U | Day 35 (정적파일 캐싱/하위페이지 서빙)

블로그 이사 완료·2023년 2월 9일
0
post-thumbnail

정적파일 캐싱

정적파일들을 브라우저에 캐싱을 해놓지 않아 로드할 때마다 약 2~3초의 로드시간이 소요됐다

express에서 폰트/이미지/JS파일 등 정적파일들을 캐싱처리해줬다.

app.use(
  express.static(path.join(__dirname, 'build'), {
    maxAge: 2629800,
    immutable: true,
  }),
);
app.use(
  '/src',
  express.static(path.join(__dirname, 'build/src'), {
    maxAge: 2629800,
    immutable: true,
  }),
);

첫 접속 이후에는 정적파일들이 캐싱되어 밀리초 단위의 로드시간이 소요된다.

애플리케이션 탭에 Cache Storage를 확인해보면 캐싱이 잘 된 것을 볼 수 있다.

하위페이지 새로고침 시 404에러

SPA 특성 상 하나의 html파일로 모든 페이지를 다이렉트 할 수 있는데 하위 페이지에서 새로고침 하면 html파일이 서빙이 되지 않았다.

해결방법은 간단했다.

express에서 모든 주소에 대한 접근 시 index.html파일을 서빙하는 것인데, 주의할 점이 있다.

다른 api 라우터들이나 정적파일에 대한 접근 코드를 다 작성하고 맨 아래에 작성해야 정상적으로 서빙이 된다.

app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(
  express.static(path.join(__dirname, 'build'), {
    maxAge: 2629800,
    immutable: true,
  }),
);
app.use(
  '/src',
  express.static(path.join(__dirname, 'build/src'), {
    maxAge: 2629800,
    immutable: true,
  }),
);

app.use(
  cors({
    origin: ['https://www.sentenceu.co.kr', 'http://localhost:3000'],
    credentials: true,
  }),
);
app.use('/api', apiRouter);


// 모든 주소에 대한 html파일 서빙

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build/index.html'));
});

하위 페이지에서 새로고침 해도 404에러가 발생하지 않는다.

profile
https://kyledev.tistory.com/

0개의 댓글