{"id":18031925,"url":"https://github.com/meabed/next-offline-ts","last_synced_at":"2025-03-27T05:31:06.331Z","repository":{"id":37048936,"uuid":"424478975","full_name":"meabed/next-offline-ts","owner":"meabed","description":"Library to make your Next.js application work offline using service workers via Google's workbox","archived":false,"fork":false,"pushed_at":"2025-03-04T21:39:59.000Z","size":1737,"stargazers_count":6,"open_issues_count":9,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-10T20:09:15.948Z","etag":null,"topics":["cache","next-pwa","nextjs","offline","pwa","service-worker","website","workbox"],"latest_commit_sha":null,"homepage":"https://github.com/meabed/next-offline-ts","language":"TypeScript","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/meabed.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-04T05:09:58.000Z","updated_at":"2025-03-07T07:14:45.000Z","dependencies_parsed_at":"2023-02-16T13:16:16.268Z","dependency_job_id":"292e620a-50be-4135-a160-34c04ab23688","html_url":"https://github.com/meabed/next-offline-ts","commit_stats":{"total_commits":250,"total_committers":5,"mean_commits":50.0,"dds":0.516,"last_synced_commit":"0fca38f82545d4c6e65a4f7a775ad485e9894c23"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meabed%2Fnext-offline-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meabed%2Fnext-offline-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meabed%2Fnext-offline-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meabed%2Fnext-offline-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/meabed","download_url":"https://codeload.github.com/meabed/next-offline-ts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244811321,"owners_count":20514276,"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","next-pwa","nextjs","offline","pwa","service-worker","website","workbox"],"created_at":"2024-10-30T10:11:45.687Z","updated_at":"2025-03-27T05:31:05.768Z","avatar_url":"https://github.com/meabed.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\n  next-offline-ts\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-ts\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dy/next-offline-ts.svg\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/next-offline-ts\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/next-offline-ts.svg?maxAge=3600\u0026label=next-offline\u0026colorB=007ec6\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\n\u003ch5 align=\"center\"\u003e\n  Maintained, Upgraded and improved version of \u003ca href='https://github.com/hanford/next-offline'\u003enext-offline\u003c/a\u003e, written in typescript, updated and tested to fix multiple issues in the original library\n\u003c/h5\u003e\n\n\n\u003cbr/\u003e\n\n## Installation\n\n```sh\n$ npm install --save next-offline-ts\n```\n\n```sh\n$ yarn add next-offline-ts\n```\n\n## Usage\n\nThere are two important things to set up, first we need `next-offline-ts` 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-ts')\n\nconst nextConfig = {\n  ...\n}\n\nmodule.exports = withOffline(nextConfig)\n```\n\nNext we need to make sure our the 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-ts options](#next-offline-ts-options)\n- [Cache Strategies](#cache-strategies)\n- [Service worker path](#service-worker-path)\n- [next export](#next-export)\n- [Development mode](#development-mode)\n- [Contributing](#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.startsWith('/service-worker.js')) {\n        const filePath = join(__dirname, '.next', pathname);\n        res.writeHead(200, { 'content-type': 'application/javascript' });\n        res.write(readFileSync(filePath).toString());\n        res.end();\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://github.com/zeit/next.js#custom-server-and-routing)\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/meabed/next-offline-ts/tree/master/packages/now2-example). The changes to be aware of are in the [now.json](https://github.com/meabed/next-offline-ts/blob/master/packages/now2-example/now.json) and [next.config.js](https://github.com/meabed/next-offline-ts/blob/master/packages/now2-example/next.config.js).\n\n## Registering service worker\n### Compile-time registration\nBy default `next-offline-ts` 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-ts/runtime` module.\n\n```js\nimport { register, unregister } from 'next-offline-ts/runtime'\n\nclass App extends React.Component {\n  componentDidMount () {\n    register()\n  }\n  componentWillUnmount () {\n    unregister()\n  }\n  ..\n}\n```\n\nIf you're handling registration on your own, pass `dontAutoRegisterSw` to next-offline-ts.\n```js\n// next.config.js\nconst { withOffline } = require('next-offline-ts')\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 `worboxOpts` 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-ts` 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-ts')\n\nconst nextConfig = {\n  workboxOpts: {\n    ...\n  }\n}\n\nmodule.exports = withOffline(nextConfig)\n```\n\n### next-offline-ts options\nOn top of the workbox options, next-offline-ts 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-ts will not generate a service worker and will instead try to modify workboxOpts.swSrc\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-ts 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-ts during development. By default, next-offline-ts 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-ts` has the following blanket runtime caching strategy. If you customize `next-offline-ts` 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-ts')\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-ts` 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-ts` 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-ts` 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-ts')\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-ts@6.0.0 we've rewritten the export functionality to work in more cases, more reliably, with less code thanks to some 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\u003chr /\u003e\n\nQuestions? Feedback? [Please let me know](https://github.com/meabed/next-offline-ts/issues/new)\n\n## TODO\n- Fix test\n- Deploy examples\n- Update documentation about caching public assets `nextAssetDirectory` and `cacheStaticAsset`\n\n## Contributing\nPlease feel free to open issues, ask questions and solve issues - All contributions are welcome\n\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 © 2021-present\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%2Fmeabed%2Fnext-offline-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmeabed%2Fnext-offline-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmeabed%2Fnext-offline-ts/lists"}