[React] 프론트엔드에서 PWA 적용하기
내가 회사에서 개발에 참여한 첫 번째 웹 사이트는 mobile-first로, '주요 사용자가 모바일을 통해 유입한다.'는 가정하에 앱처럼 만들어졌다. 네이티브 앱과 비교했을 때 웹은 오프라인 지원이나 푸시 알림 등 지원되지 않는 단점이 있다.
이러한 단점을 극복하기 위해 나온 것이 바로 Progressive Web App, PWA이다.
별도의 네이티브 앱 개발 없이 웹 기술만으로도 네이티브 앱이 가진 장점을 제공할 수 있다.
Progressive Web App
웹은 검색이 쉽고 많은 사람들이 어플리케이션을 설치하는 것을 꺼리는 경향이 있는데 PWA는 쉽게 링크로 공유할 수 있고,
또 홈화면에 추가도 빠르게 가능하다.
네이티브 앱은 오프라인 상태에서도 캐시된 데이터를 통해 동작 가능하며,이를 통해 빠르게 앱에 접속할 수 있고, 푸시 알림도 받을 수 있다. PWA는 이러한 웹과 네이티브 앱을 장점을 결합해놓은 형태의 웹 앱이다.
manifest.json 설정하기
먼저 public/manifest.json을 추가해 웹 앱의 이름, 아이콘, 배경 색상 등 기본 정보를 지정할 수 있다.
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
service worker 설정하기
cra로 프로젝트를 깔면 항상 기본적으로 깔려있고 기본 셋팅에서 지웠던 바로 그 파일이었다.
정확한 역할을 모르고 쓰지 않아서 지웠던 파일인데 이번 기회를 통해 새롭게 공부하게 되었다.
Service Worker는 브라우저 백그라운드에서 동작하는 스크립트로, 웹 앱의 작업을 보조하고 추가 기능을 제공하는 역할을 한다.
1. 오프라인 지원: Service Worker를 사용하여 웹 앱의 콘텐츠를 캐싱하여 오프라인 상태에서도 사용자가 앱을 이용할 수 있도록 합니다. 캐싱된 리소스를 이용하여 기본적인 사용자 경험을 제공하거나 일부 기능을 오프라인에서도 사용 가능하게 합니다.
2. 빠른 로딩 속도: Service Worker를 통해 콘텐츠를 브라우저 캐시에 저장하므로, 다음에 웹 앱에 접속할 때 콘텐츠를 더 빠르게 로딩할 수 있습니다.
3. 백그라운드 동기화: Service Worker를 사용하여 웹 앱이 백그라운드에서 동기화 작업을 수행하도록 할 수 있습니다. 예를 들어, 오프라인 상태에서 사용자가 데이터를 저장하면, Service Worker가 온라인 상태가 되었을 때 서버와 동기화 작업을 수행합니다.
4. 푸시 알림: Service Worker를 이용하여 푸시 알림을 지원할 수 있습니다. 서버에서 클라이언트로 푸시 알림을 보내어 사용자에게 알림을 표시할 수 있습니다.
5. 자원 관리: Service Worker는 웹 앱의 자원을 관리하는데 도움을 줍니다. 캐싱 정책을 구성하여 어떤 자원을 캐시에 저장하고 언제 삭제할지 결정할 수 있습니다.
service-worker는 cra 설치 시 자동으로 설치되는 템플릿을 가져왔다.
// service-worker.ts
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.
// serviceWorkerRegisteration.ts
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = process.env.PUBLIC_URL ? new URL(process.env.PUBLIC_URL, window.location.href) : undefined;
if (publicUrl && publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1)) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
마지막으로 index.tsx 파일에 register 해주는 것 잊지 말기
// index.tsx
// ...
root.render(
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<CookiesProvider>
<App />
</CookiesProvider>
</BrowserRouter>
</QueryClientProvider>
);
serviceWorkerRegistration.register();
간단한 듯 안 간단한 PWA 적용하기 끝~!
+ HTTPS 환경에서만 동작한다!
참고자료
https://developer.mozilla.org/ko/docs/Web/Progressive_web_apps
https://create-react-app.dev/docs/making-a-progressive-web-app/