### Install and Start Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/lifecycle/README.md Commands to install dependencies, build the project, and start the application for the lifecycle example. ```bash cd examples/lifecycle yarn install yarn build yarn start ``` -------------------------------- ### Install, Build, and Start Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/offline-fallback/README.md Commands to install dependencies, build the project, and start the offline fallback example. ```bash cd examples/offline-fallback yarn install yarn build yarn start ``` -------------------------------- ### Install and Run Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/next-image/README.md Commands to install dependencies, build the project, and start the example application. ```bash cd examples/next-image yarn install yarn build yarn start ``` -------------------------------- ### Install, Build, and Start Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/next-i18next/README.md Commands to install dependencies, build the project, and start the application in the next-i18next example directory. ```bash cd examples/next-i18next yarn install yarn build yarn start ``` -------------------------------- ### Install, Build, and Start Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/cookie/README.md Commands to install dependencies, build the project, and start the application in the cookie example directory. ```bash cd examples/cookie yarn install yarn build yarn start ``` -------------------------------- ### Install and Run next-pwa Minimal Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/minimal/README.md This snippet shows the basic commands to install dependencies, build the project, and start the minimal next-pwa example using Yarn. ```bash cd examples/minimal yarn install yarn build yarn start ``` -------------------------------- ### Install, Build, and Start Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/cache-on-front-end-nav/README.md Commands to install dependencies, build the Next.js application, and start the server for the cache-on-front-end-nav example. ```bash cd examples/cache-on-front-end-nav yarn install yarn build yarn start ``` -------------------------------- ### Install, Build, and Start Project Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/offline-fallback-v2/README.md Commands to install dependencies, build the project, and start the server for the next-pwa offline fallback example. This is a standard workflow for Next.js projects using Yarn. ```bash cd examples/offline-fallback-v2 yarn install yarn build yarn start ``` -------------------------------- ### Install and Run Next.js PWA Example Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/next-9/README.md This snippet shows the basic commands to install dependencies, build the project, and start the Next.js application with next-pwa integration. ```bash cd examples/next-9 yarn install yarn build yarn start ``` -------------------------------- ### Build and Start Application Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/web-push/README.md Commands to build the project and start the application after setting up web push. ```bash yarn build yarn start ``` -------------------------------- ### Project Build and Start Commands Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-ts-worker/README.md Provides the necessary commands to install dependencies, build the project, and start the application after setting up the custom worker configuration. ```bash cd examples/custom-ts-server yarn install yarn build yarn start ``` -------------------------------- ### Project Build and Start Commands Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-worker/README.md Provides the necessary bash commands to install dependencies, build the project, and start the application after setting up next-pwa with custom worker functionality. ```bash cd examples/custom-server yarn install yarn build yarn start ``` -------------------------------- ### PWA Manifest File Example Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md A sample `manifest.json` file to define the PWA's metadata, including name, icons, theme colors, start URL, and display mode. This file is crucial for how the PWA is presented to the user and how it behaves when installed. ```json { "name": "PWA App", "short_name": "App", "icons": [ { "src": "/icons/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" }, { "src": "/icons/android-chrome-384x384.png", "sizes": "384x384", "type": "image/png" }, { "src": "/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#FFFFFF", "background_color": "#FFFFFF", "start_url": "/", "display": "standalone", "orientation": "portrait" } ``` -------------------------------- ### Install and Generate VAPID Keys Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/web-push/README.md Steps to install dependencies and generate VAPID keys for web push notifications. ```bash cd examples/web-push yarn install yarn vapid ``` -------------------------------- ### Next.js Configuration with next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Example of how to configure next-pwa in the `next.config.js` file, including the `dest` option and commented-out examples for other common configurations. ```javascript const withPWA = require('next-pwa')({ dest: 'public' // disable: process.env.NODE_ENV === 'development', // register: true, // scope: '/app', // sw: 'service-worker.js', //... }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### Install next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Installs the next-pwa package using Yarn. ```bash yarn add next-pwa ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/web-push/README.md A recommended .gitignore configuration to exclude generated service worker and public assets. ```gitignore **/public/workbox-*.js **/public/sw.js **/public/worker-*.js ``` -------------------------------- ### next-pwa Configuration Example Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md An example of how to configure next-pwa in next.config.js, including options for reload behavior, custom worker directory, and Workbox modes. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, pwa: { dest: 'public', register: true, skipWaiting: true, disable: process.env.NODE_ENV === 'development', reloadOnOnline: true, customWorkerDir: 'worker', // Example of passing Workbox options // workboxOptions: { // disableDevLogs: true, // }, }, }; module.exports = nextConfig; ``` -------------------------------- ### Environment Variables for Web Push Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/web-push/README.md Configuration of environment variables required for web push, including email, private key, and public key. ```env WEB_PUSH_EMAIL=user@example.com WEB_PUSH_PRIVATE_KEY= NEXT_PUBLIC_WEB_PUSH_PUBLIC_KEY= ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/cookie/README.md A recommended .gitignore file content for next-pwa projects to exclude generated service worker files. ```text **/public/workbox-*.js **/public/sw.js ``` -------------------------------- ### Custom Service Worker Registration and Event Handling Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/lifecycle/README.md Example of manually registering the service worker using window.workbox and adding an event listener for updates. ```javascript import { useEffect } from 'react'; function MyApp({ Component, pageProps }) { useEffect(() => { if ('serviceWorker' in navigator) { // Register the service worker window.workbox.register('/sw.js').then(registration => { console.log('SW registered:', registration); // Listen for updates registration.addEventListener('updatefound', () => { const installingWorker = registration.installing; installingWorker.state === 'installed' && navigator.serviceWorker.controller; if (installingWorker.state === 'installed') { console.log('New content is available!'); // Optionally prompt user to reload if (confirm('A new version is available. Reload to update?')) { window.location.reload(); } } }); }).catch(error => { console.log('SW registration failed:', error); }); } }, []); return ; } export default MyApp; ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/next-9/README.md Specifies files generated by next-pwa that should be ignored by Git, ensuring clean version control. ```gitignore **/public/workbox-*.js **/public/sw.js ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/cache-on-front-end-nav/README.md A recommended .gitignore configuration for next-pwa projects to exclude generated service worker and workbox files from version control. ```gitignore **/public/workbox-*.js **/public/sw.js **/public/worker-*.js ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/next-image/README.md Specifies files to ignore in version control, specifically related to service worker generated files by next-pwa. ```ignore **/public/workbox-*.js **/public/sw.js ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-ts-worker/README.md Lists the files generated by `next-pwa` that should typically be ignored in your `.gitignore` file to prevent version control conflicts. ```bash **/public/workbox-*.js **/public/sw.js **/public/worker-*.js ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/offline-fallback/README.md Specifies files to ignore in the .gitignore file when using next-pwa, specifically Workbox generated files. ```javascript **/public/workbox-*.js **/public/sw.js ``` -------------------------------- ### Recommended .gitignore for next-pwa Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/lifecycle/README.md Files to ignore in the .gitignore file when using next-pwa to prevent caching of service worker files. ```bash **/public/precache.*.js **/public/sw.js ``` -------------------------------- ### next-pwa Fallback Configuration Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/offline-fallback-v2/README.md Configuration object for `next-pwa` to define fallback routes for various resource types like images, documents, fonts, audio, and video. This allows specifying custom pages or files to serve when the original resource cannot be fetched, typically due to network issues. ```javascript pwa: { // ... fallbacks: { image: '/static/images/fallback.png', // document: '/other-offline', // if you want to fallback to a custom page other than /_offline // font: '/static/font/fallback.woff2', // audio: ..., // video: ..., }, // ... } ``` -------------------------------- ### Configure Custom Worker Directory Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-worker/README.md Shows how to specify a custom directory for your service worker files in next.config.js. This allows next-pwa to automatically detect and bundle your custom worker code. ```javascript const withPWA = require('next-pwa')({ customWorkerDir: 'serviceworker' ... }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### next-pwa Configuration with InjectManifest Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Example of configuring next-pwa to use InjectManifest by specifying `swSrc`. This allows for more control over the service worker generation process. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, pwa: { dest: 'public', register: true, skipWaiting: true, disable: process.env.NODE_ENV === 'development', // Specify swSrc to use InjectManifest plugin swSrc: 'public/sw-src.js', // Other options can be passed to workbox-webpack-plugin // workboxOptions: { // globPatterns: ['**/*.{js,css,png,jpg,svg}'], // modifyUrlPrefix: { // '': '/_next/static/', // }, // }, }, }; module.exports = nextConfig; ``` -------------------------------- ### Next.js Configuration for Custom Registration Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/lifecycle/README.md Configuration for next.config.js to disable automatic service worker registration and enable custom control. ```javascript module.exports = { // ... pwa: { dest: 'public', register: false // Disable automatic registration } // ... } ``` -------------------------------- ### Configure Custom Worker Directory Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-ts-worker/README.md Shows how to specify a custom directory for your service worker files in `next.config.js` using the `customWorkerDir` option. This allows `next-pwa` to automatically detect and bundle your custom worker code. ```javascript const withPWA = require('next-pwa')({ customWorkerDir: 'serviceworker' // ... }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### Import Custom Worker Script Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-ts-worker/README.md Demonstrates the older method of integrating a custom service worker script by using the `importScripts` option in `next.config.js`. The specified script will be imported and executed by the generated service worker. ```javascript const withPWA = require('next-pwa')({ dest: 'public', importScripts: ['/worker.js'] }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### Import Custom Worker Script Source: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-worker/README.md Demonstrates the older method of including a custom worker script by placing it in the 'public' folder and using the 'importScripts' option in next.config.js. The generated service worker will import this script. ```javascript const withPWA = require('next-pwa')({ dest: 'public', importScripts: ['/worker.js'] }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### next-pwa Configuration Options Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Configuration options for next-pwa, including reload behavior on network connection and customization of the worker directory. ```javascript { // Changes the behavior of the app when the device detects it has gone back "online" and has a network connection. // Indicate if the app should call `location.reload()` to refresh the app. reloadOnOnline: true, // Customize the directory where `next-pwa` looks for a custom worker implementation. // For more information, check out the [custom worker example](https://github.com/shadowwalker/next-pwa/tree/master/examples/custom-ts-worker). customWorkerDir: 'worker' } ``` -------------------------------- ### Service Worker Communication Pattern Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md A recommended pattern for communicating with the service worker using `postMessage`. Use a convention like `{command: 'doSomething', message: ''}` to handle multiple tasks. ```javascript // In your application code: if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage({ command: 'syncData', message: 'User initiated sync' }); } // In your service worker (e.g., sw.js): self.addEventListener('message', (event) => { if (event.data.command === 'syncData') { console.log('Received syncData command:', event.data.message); // Perform sync operation } }); ``` -------------------------------- ### Basic Usage withPWA Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Configures next.config.js to use the withPWA higher-order function, specifying the output directory for service worker files. ```javascript const withPWA = require('next-pwa')({ dest: 'public' }) module.exports = withPWA({ // next.js config }) ``` -------------------------------- ### Runtime Caching Configuration Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Customizing runtime caching rules by copying the default cache.js and modifying it. Configurations need to be injected into the 'pwa' config in next.config.js. ```javascript // Copy default cache.js and customize rules. // Inject configurations into the 'pwa' config in next.config.js. // See Workbox documentation for writing runtime caching configurations: // https://developer.chrome.com/docs/workbox/reference/workbox-build/#type-RuntimeCaching ``` -------------------------------- ### Forcing Production Build Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Force next-pwa to generate a production build of the worker even during development by specifying `mode: 'production'` in the 'pwa' configuration. ```javascript { pwa: { mode: 'production' // ... other pwa options } } ``` -------------------------------- ### Essential PWA Head Meta Tags Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md A collection of HTML meta tags to be included in the `` component of your Next.js application (`_document.jsx` or `_app.tsx`). These tags configure various aspects of the PWA, such as application name, icons, theme colors, and display modes for different platforms (iOS, Android, Windows). ```html ``` -------------------------------- ### Viewport Meta Tag for Responsive Design Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md A viewport meta tag configured for optimal PWA display. It ensures proper scaling, prevents user zooming, and sets the viewport fit to cover, which is essential for a consistent experience on mobile devices. ```typescript ``` -------------------------------- ### Workbox Webpack Plugin Options Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md next-pwa utilizes workbox-webpack-plugin. Additional options can be passed to the 'pwa' object, which are then forwarded to GenerateSW or InjectManifest plugins. ```javascript // Options for GenerateSW or InjectManifest can be passed here. // Refer to Workbox documentation for details: // https://developer.chrome.com/docs/workbox/modules/workbox-webpack-plugin ``` -------------------------------- ### Next-PWA Configuration Options Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md This section details the various configuration options available for the next-pwa plugin in a Next.js project. These options control the behavior of PWA features, service worker generation, caching strategies, and file precaching. ```APIDOC disable: boolean - Description: Whether to disable the PWA feature entirely. - Default: `false` - Usage: Set to `false` to generate the service worker in both development and production. Set to `true` to completely disable PWA. Can be set to `process.env.NODE_ENV === 'development'` if service worker debugging in development is not needed. register: boolean - Description: Whether the plugin should register the service worker. - Default: `true` - Usage: Set to `false` if you want to handle service worker registration manually (e.g., in `componentDidMount` of your root app). Refer to `register.js` for an example. scope: string - Description: The URL scope for the PWA. - Default: `basePath` in `next.config.js` or `/`. - Usage: Set to `/app` to make paths under `/app` PWA-enabled while others are not. sw: string - Description: The name of the service worker script file. - Default: `/sw.js` - Usage: Specify a different filename to customize the output file name. runtimeCaching: Array | function - Description: Defines caching strategies for the service worker. - Default: Refer to the **Runtime Caching** section for default configuration. - Usage: Accepts an array of cache entry objects following the structure defined by Workbox ([https://developer.chrome.com/docs/workbox/reference/workbox-build/#type-RuntimeCaching](https://developer.chrome.com/docs/workbox/reference/workbox-build/#type-RuntimeCaching)). The order of rules matters; the first matching rule is effective. Place broader scope rules after specific ones. publicExcludes: Array - Description: An array of glob patterns to exclude files in the `public` folder from being precached. - Default: `['!noprecache/**/*']` (precaches all files in `public` except those in `/public/noprecache`). - Usage: Example: `['!img/super-large-image.jpg', '!fonts/not-used-fonts.otf']`. buildExcludes: Array - Description: An array of patterns or functions to exclude files from being precached in the `.next/static` folder. - Default: `[]` - Usage: Example: `[/chunks\/images\/.*$/]` to exclude files under `.next/static/chunks/images`. This is recommended when using `next-optimized-images`. The patterns follow Webpack's `exclude` option rules. cacheStartUrl: boolean - Description: Whether to cache the start URL. - Default: `true` - Discussion: See [https://github.com/shadowwalker/next-pwa/pull/296#issuecomment-1094167025](https://github.com/shadowwalker/next-pwa/pull/296#issuecomment-1094167025) for use cases where caching the start URL might be undesirable. dynamicStartUrl: boolean - Description: Set to `true` if your start URL returns different HTML documents based on state (e.g., logged in vs. logged out). - Default: `true` - Effective when `cacheStartUrl` is `true`. - Recommendation: Set to `false` if the start URL always returns the same HTML document to improve first load speed by precaching it. dynamicStartUrlRedirect: string | undefined - Description: If your start URL redirects to another route (e.g., `/login`), setting this to the redirected URL is recommended for a better user experience. - Default: `undefined` - Effective when `dynamicStartUrl` is `true`. fallbacks: object - Description: Configures precached routes to serve as fallbacks when both the cache and network are unavailable. - Default: `object` - Usage: If you need a simple offline fallback page, create a `pages/_offline.js` page; no further configuration is needed. - `fallbacks.document`: Fallback route for pages. Defaults to `/_offline` if the page exists. - `fallbacks.image`: Fallback route for images. Defaults to none. - `fallbacks.audio`: Fallback route for audio. Defaults to none. - `fallbacks.video`: Fallback route for video. Defaults to none. - `fallbacks.font`: Fallback route for fonts. Defaults to none. cacheOnFrontEndNav: boolean - Description: Enables additional route caching during front-end navigation using `next/link`. - Default: `false` - Context: See example at [https://github.com/shadowwalker/next-pwa/tree/master/examples/cache-on-front-end-nav](https://github.com/shadowwalker/next-pwa/tree/master/examples/cache-on-front-end-nav). This improves user experience in specific cases but adds overhead due to extra network calls. Consider this as a trade-off. ~~subdomainPrefix: string~~ - Description: URL prefix for hosting static files on a subdomain. Deprecated; use `basePath` instead. - Default: `""` (no prefix). - Example: `/subdomain` if the app is hosted on `example.com/subdomain`. ``` -------------------------------- ### Workbox Cacheable Response Configuration Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Demonstrates how to configure Workbox's `cacheableResponse` to include specific HTTP status codes, such as 302 redirects, in addition to the default 200. ```APIDOC RuntimeCachingRule: urlPattern: string | RegExp | ((request: Request) => boolean) handler: 'CacheFirst' | 'NetworkFirst' | 'CacheOnly' | 'NetworkOnly' | 'StaleWhileRevalidate' options?: { cacheName?: string expiration?: { maxEntries?: number maxAgeSeconds?: number templateVariables?: Record } matchOptions?: CacheQueryOptions // Allows specifying which HTTP status codes are considered cacheable. // By default, only 200 OK responses are cached. cacheableResponse?: { statuses?: number[] // Allows specifying which HTTP headers are considered cacheable. // headers?: string[] } } ``` -------------------------------- ### Custom Server Configuration for Service Workers Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md Configures a custom Node.js server using Express to serve static files, specifically for PWA service worker scripts like 'sw.js' and Workbox-generated files. It integrates with Next.js's request handler to manage other application routes. ```javascript const { createServer } = require('http') const { join } = require('path') const { parse } = require('url') const next = require('next') const app = next({ dev: process.env.NODE_ENV !== 'production' }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname } = parsedUrl if (pathname === '/sw.js' || /^/(workbox|worker|fallback)-\w+\.js$/.test(pathname)) { const filePath = join(__dirname, '.next', pathname) app.serveStatic(req, res, filePath) } else { handle(req, res, parsedUrl) } }).listen(3000, () => { console.log(`> Ready on http://localhost:${3000}`) }) }) ``` -------------------------------- ### Debugging Service Worker Cacheable Response Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md When redirecting users, Workbox by default only caches responses with a 200 HTTP status. To cache redirected pages, specify additional statuses like 302 in runtimeCaching options. ```javascript { // ... other options runtimeCaching: [ { // ... other runtimeCaching options options: { cacheableResponse: { statuses: [200, 302] } } } ] } ``` -------------------------------- ### Disabling Development Logs in Custom Worker Source: https://github.com/shadowwalker/next-pwa/blob/master/README.md To disable development logs in the service worker while keeping the development build, set `self.__WB_DISABLE_DEV_LOGS = true` in your custom worker file (e.g., worker/index.js). ```javascript // In your custom worker file (e.g., worker/index.js) self.__WB_DISABLE_DEV_LOGS = true; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.