{"id":13433780,"url":"https://github.com/hanford/next-offline","last_synced_at":"2025-04-13T03:59:44.923Z","repository":{"id":37677622,"uuid":"120654902","full_name":"hanford/next-offline","owner":"hanford","description":"make your Next.js application work offline using service workers via Google's workbox","archived":false,"fork":false,"pushed_at":"2023-01-03T23:02:48.000Z","size":2465,"stargazers_count":1595,"open_issues_count":58,"forks_count":110,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-04-13T03:59:39.500Z","etag":null,"topics":["cache","nextjs","offline","pwa","service-worker","website","workbox"],"latest_commit_sha":null,"homepage":"https://github.com/hanford/next-offline","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hanford.png","metadata":{"files":{"readme":"readme.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-02-07T18:33:43.000Z","updated_at":"2025-04-07T18:36:10.000Z","dependencies_parsed_at":"2023-02-01T12:30:39.370Z","dependency_job_id":null,"html_url":"https://github.com/hanford/next-offline","commit_stats":null,"previous_names":[],"tags_count":130,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanford%2Fnext-offline","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanford%2Fnext-offline/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanford%2Fnext-offline/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanford%2Fnext-offline/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hanford","download_url":"https://codeload.github.com/hanford/next-offline/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248661706,"owners_count":21141450,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","nextjs","offline","pwa","service-worker","website","workbox"],"created_at":"2024-07-31T02:01:35.973Z","updated_at":"2025-04-13T03:59:44.901Z","avatar_url":"https://github.com/hanford.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Nextjs Plugins","📦 Legacy \u0026 Inactive Projects"],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\n  next-offline\n\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\nUse \u003ca href='https://github.com/GoogleChrome/workbox'\u003eWorkbox\u003c/a\u003e with \u003ca href='https://github.com/zeit/next.js'\u003e\nNext.js\u003c/a\u003e and \u003cbr /\u003eeasily enable offline functionality in your application!\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/next-offline\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dy/next-offline.svg\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/next-offline\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/next-offline.svg?maxAge=3600\u0026label=next-offline\u0026colorB=007ec6\"\u003e\n  \u003c/a\u003e\n  \u003cimg src=\"https://img.shields.io/github/repo-size/hanford/next-offline.svg\" /\u003e\n\u003c/p\u003e\n\n\u003cbr/\u003e\n\n## Installation\n\n```sh\n$ npm install --save next-offline\n```\n\n```sh\n$ yarn add next-offline\n```\n\n## Usage\n\nThere are two important things to set up, first we need `next-offline` to wrap your next config.\n\nIf you haven't yet, create a `next.config.js` in your project.\n\n```js\n// next.config.js\nconst withOffline = require('next-offline')\n\nconst nextConfig = {\n  ...\n}\n\nmodule.exports = withOffline(nextConfig)\n```\n\nNext we need to make sure our application is properly serving the service worker, this setup depends on how you're hosting your application. There is [documentation](#serving-service-worker) below. If you're not using Now 2.0, the Now 1.0 example should work in most circumstances.\n\n## Documentation\n- [Serving service worker](#serving-service-worker)\n  - [Now 1.0 / AWS](#now-10)\n  - [Now 2.0](#now-20)\n- [Registering service worker](#registering-service-worker)\n  - [compile-time registration](#compile-time-registration)\n  - [runtime registration](#runtime-registration)\n- [Customizing service worker](#customizing-service-worker)\n  - [Using workbox](#using-workbox)\n  - [next-offline options](#next-offline-options)\n- [Cache Strategies](#cache-strategies)\n- [Service worker path](#service-worker-path)\n- [next export](#next-export)\n- [Development mode](#development-mode)\n- [Next Offline 5.0](#next-offline-50)\n- [Contrbuting](#contributing)\n- [License](#license-(mit))\n\n## Serving service worker\nBecause service workers are so powerful, the API has some restrictions built in. For example, service workers must be served on the domain they're being used on - [you can't use a CDN](https://github.com/w3c/ServiceWorker/issues/940).\n\n### Now 1.0\nYou'll want to use the next.js custom server API. The easiest way to do that is creating a `server.js` that looks like this:\n```js\nconst { createServer } = require('http')\nconst { join } = require('path')\nconst { parse } = require('url')\nconst next = require('next')\n\nconst app = next({ dev: process.env.NODE_ENV !== 'production' })\nconst handle = app.getRequestHandler()\n\napp.prepare()\n  .then(() =\u003e {\n    createServer((req, res) =\u003e {\n      const parsedUrl = parse(req.url, true)\n      const { pathname } = parsedUrl\n\n      // handle GET request to /service-worker.js\n      if (pathname === '/service-worker.js') {\n        const filePath = join(__dirname, '.next', pathname)\n\n        app.serveStatic(req, res, filePath)\n      } else {\n        handle(req, res, parsedUrl)\n      }\n    })\n    .listen(3000, () =\u003e {\n      console.log(`\u003e Ready on http://localhost:${3000}`)\n    })\n  })\n```\nYou can  read more about custom servers in the [Next.js docs](https://nextjs.org/docs/advanced-features/custom-server)\n\nIf you're not hosting with Now, I'd probably follow the Now 1.0 approach because the custom server API can enable a lot of functionality, it just simply doesn't work well with Now 2.0 🙇‍♂️\n\n### Now 2.0\nBecause Now 2.0 works so different than the previous version, so does serving the service worker. There are a few different ways to do this, but I'd recommend checking out [this now2 example app](https://github.com/hanford/next-offline/tree/master/packages/now2-example). The changes to be aware of are in the [now.json](https://github.com/hanford/next-offline/blob/master/packages/now2-example/now.json) and [next.config.js](https://github.com/hanford/next-offline/blob/master/packages/now2-example/next.config.js).\n\n## Registering service worker\n### Compile-time registration\nBy default `next-offline` will register a service worker with the script below, this is automatically added to your client side bundle once `withOffline` is invoked.\n\n```js\nif ('serviceWorker' in navigator) {\n  window.addEventListener('load', function () {\n    navigator.serviceWorker.register('/service-worker.js', { scope: '/' }).then(function (registration) {\n      console.log('SW registered: ', registration)\n    }).catch(function (registrationError) {\n      console.log('SW registration failed: ', registrationError)\n    })\n  })\n}\n```\n\n### Runtime registration\nAlternative to compile-time, you can take control of registering/unregistering in your application code by using the `next-offline/runtime` module.\n\n```js\nimport { register, unregister } from 'next-offline/runtime'\n\nclass App extends React.Component {\n  componentDidMount () {\n    register()\n  }\n  componentWillUnmount () {\n    unregister()\n  }\n  ..\n}\n```\n\nYou can choose to pass the service worker path and scope if needed. \n```js\nimport { register, unregister } from 'next-offline/runtime'\n\nclass App extends React.Component {\n  componentDidMount () {\n    /** \n      * Default service worker path is '/service-worker.js' \n      * Refer https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register for default scope rules\n      *\n    */\n    register('/sub_folder/service-worker.js', {scope: '/sub_folder'}) \n  }\n  componentWillUnmount () {\n    unregister()\n  }\n  ..\n}\n```\n\nIf you're handling registration on your own, pass `dontAutoRegisterSw` to next-offline.\n```js\n// next.config.js\nconst withOffline = require('next-offline')\n\nmodule.exports = withOffline({ dontAutoRegisterSw: true })\n```\n\n## Customizing service worker\n\n### Using workbox\n\nIf you're new to workbox, I'd recommend reading this [quick guide](https://developers.google.com/web/tools/workbox/guides/generate-service-worker/webpack#adding_runtime_caching) -- anything inside of `workboxOpts` will be passed to `workbox-webpack-plugin`.\n\nDefine a `workboxOpts` object in your `next.config.js` and it will gets passed to [workbox-webpack-plugin](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#generatesw_plugin). Workbox is what `next-offline` uses under the hood to generate the service worker, you can learn more about it [here](https://developers.google.com/web/tools/workbox/).\n\n```js\n// next.config.js\nconst withOffline = require('next-offline')\n\nconst nextConfig = {\n  workboxOpts: {\n    ...\n  }\n}\n\nmodule.exports = withOffline(nextConfig)\n```\n\n### next-offline options\nOn top of the workbox options, next-offline has some options built in flags to give you finer grain control over how your service worker gets generated.\n\n\u003ctable\u003e\n  \u003cthead\u003e\n    \u003ctr\u003e\n      \u003cth\u003eName\u003c/th\u003e\n      \u003cth\u003eType\u003c/th\u003e\n      \u003cth\u003eDescription\u003c/th\u003e\n      \u003cth\u003eDefault\u003c/th\u003e\n    \u003c/tr\u003e\n  \u003c/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd\u003egenerateSw\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003eIf false, next-offline will not generate a service worker and will instead try to modify the file found in workboxOpts.swSrc using WorkBox's [Inject Plugin](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#injectmanifest_plugin)\u003c/td\u003e\n      \u003ctd\u003etrue\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003edontAutoRegisterSw\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003eIf true, next-offline won't automatically push the registration script into the application code. This is required if you're using runtime registration or are handling registration on your own.\u003c/td\u003e\n      \u003ctd\u003efalse\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003edevSwSrc\u003c/td\u003e\n      \u003ctd\u003eString\u003c/td\u003e\n      \u003ctd\u003ePath to be registered by next-offline during development. By default next-offline will register a noop during development\u003c/td\u003e\n      \u003ctd\u003efalse\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003egenerateInDevMode\u003c/td\u003e\n      \u003ctd\u003eBoolean\u003c/td\u003e\n      \u003ctd\u003eIf true, the service worker will also be generated in development mode. Otherwise the service worker defined in devSwSrc will be used.\u003c/td\u003e\n      \u003ctd\u003efalse\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eregisterSwPrefix\u003c/td\u003e\n      \u003ctd\u003eString\u003c/td\u003e\n      \u003ctd\u003eIf your service worker isn't at the root level of your application, this can help you prefix the path. This is useful if you'd like your service worker on foobar.com/my/long/path/service-worker.js. This affects the [scope](https://developers.google.com/web/ilt/pwa/introduction-to-service-worker#registration_and_scope) of your service worker.\u003c/td\u003e\n      \u003ctd\u003efalse\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003escope\u003c/td\u003e\n      \u003ctd\u003eString\u003c/td\u003e\n      \u003ctd\u003eThis is passed to the automatically registered service worker allowing increase or decrease what the service worker has control of.\u003c/td\u003e\n      \u003ctd\u003e\"/\"\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\n## Cache strategies\nBy default `next-offline` has the following blanket runtime caching strategy. If you customize `next-offline` with `workboxOpts`, the default behaviour will not be passed into `workbox-webpack-plugin`. This [article](https://developers.google.com/web/tools/workbox/guides/generate-service-worker/webpack#adding_runtime_caching) is great at breaking down various different cache recipes.\n```js\n{\n  runtimeCaching: [\n    {\n      urlPattern: /^https?.*/,\n      handler: 'NetworkFirst',\n      options: {\n        cacheName: 'offlineCache',\n        expiration: {\n          maxEntries: 200\n        }\n      }\n    }\n  ]\n}\n```\n\n\n```js\n// next.config.js\nconst withOffline = require('next-offline')\n\nmodule.exports = withOffline({\n  workboxOpts: {\n    runtimeCaching: [\n      {\n        urlPattern: /.png$/,\n        handler: 'CacheFirst'\n      },\n      {\n        urlPattern: /api/,\n        handler: 'NetworkFirst',\n        options: {\n          cacheableResponse: {\n            statuses: [0, 200],\n            headers: {\n              'x-test': 'true'\n            }\n          }\n        }\n      }\n    ]\n  }\n})\n```\n\n## Service worker path\nIf your application doesn't live on the root of your domain, you can use `registerSwPrefix`. This is helpful if your application is on domain.com/my/custom/path because by default `next-offline` assumes your application is on domain.com and will try to register domain.com/service-worker.js. We can't support using `assetPrefix` because service workers must be served on the root domain. For a technical breakdown on that limitation, see the following link: [Is it possible to serve service workers from CDN/remote origin?](https://github.com/w3c/ServiceWorker/issues/940)\n\nBy default `next-offline` will precache all the Next.js webpack emitted files and the user-defined static ones (inside `/static`) - essentially everything that is exported as well.\n\nIf you'd like to include some more or change the origin of your static files use the given workbox options:\n\n```js\nworkboxOpts: {\n  modifyURLPrefix: {\n    'app': assetPrefix,\n  },\n  runtimeCaching: {...}\n}\n```\n\n## Development mode\nBy default `next-offline` will add a no-op service worker in development. If you want to provide your own pass its filepath to `devSwSrc` option. This is particularly useful if you want to test web push notifications in development, for example.\n\n```js\n// next.config.js\nconst withOffline = require('next-offline')\n\nmodule.exports = withOffline({\n  devSwSrc: '/path/to/my/dev/service-worker.js'\n})\n```\n\nYou can disable this behavior by setting the `generateInDevMode` option to `true`.\n\n\n## next export\n\nIn next-offline@3.0.0 we've rewritten the export functionality to work in more cases, more reliably, with less code thanks to some of the additions in Next 7.0.0!\n\nYou can read more about exporting at [Next.js docs]((https://github.com/zeit/next.js#static-html-export)) but next offline should Just Work™️.\n\n## next offline 5.0\nIf you're upgrading to the latest version of `next-offline` I recommend glancing at what's been added/changed inside of [Workbox in 5.x releases](https://github.com/GoogleChrome/workbox/releases) along with the 4.0 release which included the [breaking changes](https://github.com/GoogleChrome/workbox/releases/tag/v4.0.0). Next Offline's API hasn't changed, but a core dependency has!\n\n\u003chr /\u003e\n\nQuestions? Feedback? [Please let me know](https://github.com/hanford/next-offline/issues/new)\n\n## Contributing\n`next-offline` is a [lerna monorepo](https://lerna.js.org/)  which uses yarn workspaces. After cloning the repo, run the following\n\n```sh\n$ yarn bootstrap\n```\n\nThis will ensure your development version of next-offline is symlinked in the examples \u0026 tests which should allow you to quickly make changes!\n\n## License (MIT)\n\n```\nWWWWWW||WWWWWW\n W W W||W W W\n      ||\n    ( OO )__________\n     /  |           \\\n    /o o|    MIT     \\\n    \\___/||_||__||_|| *\n         || ||  || ||\n        _||_|| _||_||\n       (__|__|(__|__|\n```\nCopyright © 2017-present [Jack Hanford](http://jackhanford.com), jackhanford@gmail.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhanford%2Fnext-offline","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhanford%2Fnext-offline","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhanford%2Fnext-offline/lists"}