next-offline
make your Next.js application work offline using service workers via Google's workbox
Top Related Projects
The React Framework
Zero config PWA plugin for Next.js, with workbox 🧰
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
📦 Workbox: JavaScript libraries for Progressive Web Apps
Quick Overview
Next-offline is a plugin for Next.js that enables offline support and progressive web app (PWA) functionality. It simplifies the process of adding service workers and offline capabilities to Next.js applications, allowing developers to create more robust and user-friendly web experiences.
Pros
- Easy integration with Next.js projects
- Automatic service worker generation and registration
- Customizable caching strategies
- Supports both static and dynamic content caching
Cons
- Limited documentation and examples
- May require additional configuration for complex use cases
- Potential conflicts with other Next.js plugins or custom service workers
- Maintenance and updates may lag behind Next.js releases
Code Examples
- Basic configuration in
next.config.js
:
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [
{
urlPattern: /^https?.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'https-calls',
networkTimeoutSeconds: 15,
expiration: {
maxEntries: 150,
maxAgeSeconds: 30 * 24 * 60 * 60, // 1 month
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
},
})
- Custom service worker registration in
pages/_app.js
:
import { useEffect } from 'react'
function MyApp({ Component, pageProps }) {
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then((registration) => console.log('Service Worker registered'))
.catch((err) => console.error('Service Worker registration failed', err))
}
}, [])
return <Component {...pageProps} />
}
export default MyApp
- Precaching specific pages:
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [
{
urlPattern: '/',
handler: 'NetworkFirst',
},
{
urlPattern: '/about',
handler: 'CacheFirst',
},
],
},
})
Getting Started
-
Install the package:
npm install next-offline
-
Update your
next.config.js
:const withOffline = require('next-offline') module.exports = withOffline({ // Your Next.js config here })
-
Add a custom
server.js
file to handle service worker routes:const { createServer } = require('http') const { parse } = require('url') const next = require('next') const dev = process.env.NODE_ENV !== 'production' const app = next({ dev }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname } = parsedUrl if (pathname === '/service-worker.js') { 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') }) })
-
Update your
package.json
scripts:"scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js" }
Competitor Comparisons
The React Framework
Pros of Next.js
- Comprehensive full-stack React framework with built-in routing, server-side rendering, and API routes
- Extensive ecosystem and community support, with regular updates and improvements
- Seamless integration with Vercel's deployment platform for optimal performance
Cons of Next.js
- Larger bundle size and potentially more complex setup compared to next-offline
- May include unnecessary features for projects that only require offline functionality
- Steeper learning curve for developers new to the Next.js ecosystem
Code Comparison
next-offline:
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [/* ... */]
}
})
Next.js:
// next.config.js
module.exports = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
}
Summary
Next.js offers a more comprehensive solution for building React applications, including offline capabilities, while next-offline focuses specifically on adding offline functionality to Next.js projects. Next.js provides a wider range of features and better integration with Vercel's ecosystem, but may be overkill for simpler projects. next-offline offers a more lightweight approach for adding offline support to existing Next.js applications.
Zero config PWA plugin for Next.js, with workbox 🧰
Pros of next-pwa
- More actively maintained with frequent updates
- Offers more comprehensive PWA features, including offline support, push notifications, and app installation
- Provides better TypeScript support and integration
Cons of next-pwa
- Slightly more complex setup and configuration
- May have a steeper learning curve for beginners
- Potentially larger bundle size due to additional features
Code Comparison
next-pwa:
// next.config.js
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development'
})
module.exports = withPWA({
// your next.js config
})
next-offline:
// next.config.js
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [
// your runtime caching config
]
}
})
Both libraries aim to add offline capabilities to Next.js applications, but next-pwa offers a more comprehensive set of PWA features. next-offline focuses primarily on offline functionality, while next-pwa provides a broader range of PWA capabilities. The choice between the two depends on the specific requirements of your project and the level of PWA functionality you need.
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Pros of sw-precache-webpack-plugin
- More mature and widely used in the webpack ecosystem
- Offers fine-grained control over service worker configuration
- Supports a broader range of webpack versions
Cons of sw-precache-webpack-plugin
- Requires more manual configuration and setup
- Less integrated with Next.js framework
- May require additional plugins for full offline functionality
Code Comparison
sw-precache-webpack-plugin:
new SWPrecacheWebpackPlugin({
cacheId: 'my-project-name',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'],
minify: true,
stripPrefix: 'dist/'
})
next-offline:
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
runtimeCaching: [
{
urlPattern: /^https?.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'https-calls',
networkTimeoutSeconds: 15,
expiration: {
maxEntries: 150,
maxAgeSeconds: 30 * 24 * 60 * 60
},
cacheableResponse: {
statuses: [0, 200]
}
}
}
]
}
})
sw-precache-webpack-plugin is more versatile for webpack projects but requires more setup, while next-offline provides a simpler integration specifically for Next.js applications with built-in offline capabilities.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Pros of offline-plugin
- More mature and widely used project with a larger community
- Supports a broader range of web applications, not limited to Next.js
- Offers more advanced caching strategies and configuration options
Cons of offline-plugin
- Requires more setup and configuration compared to next-offline
- May have a steeper learning curve for developers new to service workers
- Not specifically optimized for Next.js applications
Code Comparison
offline-plugin:
const OfflinePlugin = require('offline-plugin');
module.exports = {
// ... other webpack config
plugins: [
new OfflinePlugin({
// plugin options
})
]
};
next-offline:
const withOffline = require('next-offline');
module.exports = withOffline({
// ... other Next.js config
workboxOpts: {
// Workbox options
}
});
offline-plugin provides a more generic webpack plugin approach, while next-offline integrates seamlessly with Next.js configuration. The latter requires less boilerplate code for Next.js projects, making it easier to implement offline functionality in Next.js applications.
📦 Workbox: JavaScript libraries for Progressive Web Apps
Pros of Workbox
- More comprehensive and feature-rich service worker library
- Actively maintained by Google, with frequent updates and improvements
- Supports a wide range of caching strategies and advanced PWA features
Cons of Workbox
- Steeper learning curve due to its extensive API and features
- May be overkill for simple Next.js projects that only need basic offline functionality
- Requires more configuration and setup compared to Next Offline
Code Comparison
Next Offline:
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
swDest: 'static/service-worker.js',
},
})
Workbox:
import { generateSW } from 'workbox-webpack-plugin'
module.exports = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.plugins.push(
new generateSW({
swDest: 'static/service-worker.js',
})
)
}
return config
},
}
Next Offline is specifically designed for Next.js projects and offers a simpler setup process. It's ideal for developers who want to quickly add offline functionality to their Next.js applications without diving deep into service worker configuration.
Workbox, on the other hand, is a more powerful and flexible solution that can be used with various web frameworks, including Next.js. It provides advanced caching strategies, background sync, and other PWA features, making it suitable for complex applications that require fine-grained control over offline behavior.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
next-offline
Use Workbox with
Next.js and
easily enable offline functionality in your application!
Installation
$ npm install --save next-offline
$ yarn add next-offline
Usage
There are two important things to set up, first we need next-offline
to wrap your next config.
If you haven't yet, create a next.config.js
in your project.
// next.config.js
const withOffline = require('next-offline')
const nextConfig = {
...
}
module.exports = withOffline(nextConfig)
Next 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 below. If you're not using Now 2.0, the Now 1.0 example should work in most circumstances.
Documentation
- Serving service worker
- Registering service worker
- Customizing service worker
- Cache Strategies
- Service worker path
- next export
- Development mode
- Next Offline 5.0
- Contrbuting
- License
Serving service worker
Because 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.
Now 1.0
You'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:
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
// handle GET request to /service-worker.js
if (pathname === '/service-worker.js') {
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}`)
})
})
You can read more about custom servers in the Next.js docs
If 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 ðââï¸
Now 2.0
Because 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. The changes to be aware of are in the now.json and next.config.js.
Registering service worker
Compile-time registration
By 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.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/service-worker.js', { scope: '/' }).then(function (registration) {
console.log('SW registered: ', registration)
}).catch(function (registrationError) {
console.log('SW registration failed: ', registrationError)
})
})
}
Runtime registration
Alternative to compile-time, you can take control of registering/unregistering in your application code by using the next-offline/runtime
module.
import { register, unregister } from 'next-offline/runtime'
class App extends React.Component {
componentDidMount () {
register()
}
componentWillUnmount () {
unregister()
}
..
}
You can choose to pass the service worker path and scope if needed.
import { register, unregister } from 'next-offline/runtime'
class App extends React.Component {
componentDidMount () {
/**
* Default service worker path is '/service-worker.js'
* Refer https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register for default scope rules
*
*/
register('/sub_folder/service-worker.js', {scope: '/sub_folder'})
}
componentWillUnmount () {
unregister()
}
..
}
If you're handling registration on your own, pass dontAutoRegisterSw
to next-offline.
// next.config.js
const withOffline = require('next-offline')
module.exports = withOffline({ dontAutoRegisterSw: true })
Customizing service worker
Using workbox
If you're new to workbox, I'd recommend reading this quick guide -- anything inside of workboxOpts
will be passed to workbox-webpack-plugin
.
Define a workboxOpts
object in your next.config.js
and it will gets passed to workbox-webpack-plugin. Workbox is what next-offline
uses under the hood to generate the service worker, you can learn more about it here.
// next.config.js
const withOffline = require('next-offline')
const nextConfig = {
workboxOpts: {
...
}
}
module.exports = withOffline(nextConfig)
next-offline options
On 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.
Name | Type | Description | Default |
---|---|---|---|
generateSw | Boolean | If 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) | true |
dontAutoRegisterSw | Boolean | If 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. | false |
devSwSrc | String | Path to be registered by next-offline during development. By default next-offline will register a noop during development | false |
generateInDevMode | Boolean | If true, the service worker will also be generated in development mode. Otherwise the service worker defined in devSwSrc will be used. | false |
registerSwPrefix | String | If 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. | false |
scope | String | This is passed to the automatically registered service worker allowing increase or decrease what the service worker has control of. | "/" |
Cache strategies
By 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 is great at breaking down various different cache recipes.
{
runtimeCaching: [
{
urlPattern: /^https?.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'offlineCache',
expiration: {
maxEntries: 200
}
}
}
]
}
// next.config.js
const withOffline = require('next-offline')
module.exports = withOffline({
workboxOpts: {
runtimeCaching: [
{
urlPattern: /.png$/,
handler: 'CacheFirst'
},
{
urlPattern: /api/,
handler: 'NetworkFirst',
options: {
cacheableResponse: {
statuses: [0, 200],
headers: {
'x-test': 'true'
}
}
}
}
]
}
})
Service worker path
If 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?
By 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.
If you'd like to include some more or change the origin of your static files use the given workbox options:
workboxOpts: {
modifyURLPrefix: {
'app': assetPrefix,
},
runtimeCaching: {...}
}
Development mode
By 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.
// next.config.js
const withOffline = require('next-offline')
module.exports = withOffline({
devSwSrc: '/path/to/my/dev/service-worker.js'
})
You can disable this behavior by setting the generateInDevMode
option to true
.
next export
In 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!
You can read more about exporting at Next.js docs but next offline should Just Workâ¢ï¸.
next offline 5.0
If 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 along with the 4.0 release which included the breaking changes. Next Offline's API hasn't changed, but a core dependency has!
Questions? Feedback? Please let me know
Contributing
next-offline
is a lerna monorepo which uses yarn workspaces. After cloning the repo, run the following
$ yarn bootstrap
This will ensure your development version of next-offline is symlinked in the examples & tests which should allow you to quickly make changes!
License (MIT)
WWWWWW||WWWWWW
W W W||W W W
||
( OO )__________
/ | \
/o o| MIT \
\___/||_||__||_|| *
|| || || ||
_||_|| _||_||
(__|__|(__|__|
Copyright © 2017-present Jack Hanford, jackhanford@gmail.com
Permission 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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE 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.
Top Related Projects
The React Framework
Zero config PWA plugin for Next.js, with workbox 🧰
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
📦 Workbox: JavaScript libraries for Progressive Web Apps
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot