@elken/next-offline
v3.4.0
Published
<h1 align="center"> next-offline </h1>
Downloads
4
Maintainers
Readme
Installation
$ npm install --save next-offline
$ yarn add next-offline
Usage
Create a next.config.js
in your project
// next.config.js
const withOffline = require('next-offline')
const nextConfig = {
...
}
module.exports = withOffline(nextConfig)
Documentation
- Installation
- Usage
- Documentation
- Serving service worker
- Registering service worker
- Customizing service worker
- Cache strategies
- Service worker path
- Development mode
- next export
- License (MIT)
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()
}
..
}
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
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.
further customisations
It is also possible to append your own code to the end of the serviceWorker, as shown below.
extraCodePath: "static/serviceWorker.js",
registerOverridePath: "static/init-sw.js"
extraCodePath
will append the content of the file to the end of the created serviceWorker, whereas registerOverridePath
will override the existing default register, so you will need to ensure that it is complete.
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
{
globPatterns: ['static/**/*'],
globDirectory: '.',
runtimeCaching: { urlPattern: /^https?.*/, handler: 'networkFirst' }
}
// 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: {
globPatterns: ['app/static/**/*', 'any/other/fileglob/to/cache'],
globDirectory: '.',
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 [email protected] 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™️.
Questions? Feedback? Please let me know
License (MIT)
WWWWWW||WWWWWW
W W W||W W W
||
( OO )__________
/ | \
/o o| MIT \
\___/||_||__||_|| *
|| || || ||
_||_|| _||_||
(__|__|(__|__|
Copyright © 2017-present Jack Hanford, [email protected]
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.