JSPM

  • Created
  • Published
  • Downloads 6237
  • Score
    100M100P100Q153775F
  • License MIT

Package Exports

  • next-offline

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (next-offline) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Next.js + sw-precache

Use sw-precache with Next.js

Installation

npm install --save @zeit/next-offline

or

yarn add @zeit/next-offline

Usage

Create a next.config.js in your project

// next.config.js
const withOffline = require('@zeit/next-offline')
module.exports = withOffline()

Then create a server.js

// server.js
const { createServer } = require('http')
const next = require('next')
const { join } = require('path')

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 === '/service-worker.js') {
        const filePath = join(__dirname, '.next', pathname)
        app.serveStatic(req, res, filePath)
      } else {
        handle(req, res, parsedUrl)
      }
    })
    .listen(port, () => {
      console.log(`> Ready on http://localhost:${port}`)
    })
  })

Finally you'll need to ensure you're registering the service worker in each of your pages. next-offline comes with a HOC that will wrap your component which you can see the usage below:

// pages/index.js
import withOffline from '@zeit/next-offline/hoc.js'

class Index extends PureComponent {
  ..

  render () {
    return (
      <h1>I'm the index page!</h1>
    )
  }
}

export default withOffline(Index)

Alternatively you can register the service worker manually

// pages/index.js
export default class Index extends PureComponent {
  componentDidMount () {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker
        .register('/service-worker.js')
        .then(registration => console.info('service worker registration successful'))
        .catch(err => console.warn('service worker registration failed', err.message))
    }
  }

  ..
}

Optionally you can add your custom Next.js configuration as parameter

// next.config.js
const withOffline = require('@zeit/next-offline')
module.exports = withOffline({
  webpack(config, options) {
    return config
  }
})