next-offline vs next-optimized-images vs next-pwa
Legacy vs Modern PWA and Image Optimization in Next.js
next-offlinenext-optimized-imagesnext-pwaSimilar Packages:

Legacy vs Modern PWA and Image Optimization in Next.js

next-offline, next-optimized-images, and next-pwa are third-party plugins designed to extend Next.js capabilities regarding offline support, asset optimization, and Progressive Web App (PWA) features. However, the Next.js ecosystem has evolved significantly, with core features now native to the framework. next-optimized-images is largely deprecated due to built-in image handling. next-offline is considered legacy in favor of more robust service worker solutions. next-pwa remains a popular choice for comprehensive PWA configuration but requires careful setup with modern Next.js versions.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
next-offline01,603-585 years agoMIT
next-optimized-images02,238-1326 years agoMIT
next-pwa04,08851.2 kB139-MIT

Legacy vs Modern PWA and Image Optimization in Next.js

When building production-grade Next.js applications, performance and offline capabilities are non-negotiable. Historically, developers relied on plugins like next-offline, next-optimized-images, and next-pwa to fill gaps in the framework. Today, the landscape has shifted. Next.js has absorbed many of these features into its core, rendering some packages obsolete while others remain vital for specific use cases. Let's analyze the technical realities of each.

πŸ–ΌοΈ Image Optimization: Built-In vs External Plugins

Image performance is critical for Core Web Vitals. The approach to handling this has changed drastically over recent Next.js versions.

next-optimized-images was the standard solution before Next.js 10. It allowed importing images directly in JavaScript to optimize them at build time.

// next-optimized-images: Importing images directly
import img from './image.png';

export default function Page() {
  return <img src={img} alt="Optimized" />;
}

next-offline does not handle image optimization directly. It focuses on caching assets via Service Workers. You would still need a separate solution for image transformation.

// next-offline: No image optimization API
// Relies on standard Webpack loaders or external tools
module.exports = withOffline({
  // Configuration focuses on SW, not assets
});

next-pwa also delegates image optimization to the underlying Next.js configuration. It caches the optimized assets but does not transform them itself.

// next-pwa: Caching optimized assets
const withPWA = require('next-pwa');
module.exports = withPWA({
  images: {
    // Uses native next/image config
    formats: ['image/avif', 'image/webp'],
  },
});

⚠️ Critical Note: next-optimized-images is deprecated. Modern Next.js includes the next/image component, which provides automatic resizing, formatting, and lazy loading out of the box. Using the legacy package adds unnecessary build complexity and conflicts with native features.

// βœ… Modern Next.js Native Approach
import Image from 'next/image';

export default function Page() {
  return <Image src="/image.png" width={500} height={300} alt="Native Opt" />;
}

πŸ“‘ Service Worker Strategies: Granular Control vs Convention

Offline support relies on Service Workers. The three packages offer different levels of abstraction over Workbox (the underlying library).

next-offline provides a simple wrapper. It is opinionated and aims for zero-config offline support. This is great for speed but limits customization.

// next-offline: Minimal config
const withOffline = require('next-offline');

module.exports = withOffline({
  transformManifest: (manifest) => ['/'].concat(manifest),
});

next-optimized-images has no Service Worker capabilities. It is strictly an asset loader.

// next-optimized-images: No SW support
// Cannot configure caching strategies

next-pwa offers deep configuration over Workbox. You can define caching strategies for different routes, handle runtime caching, and manage precaching lists explicitly.

// next-pwa: Advanced Workbox config
const withPWA = require('next-pwa');

module.exports = withPWA({
  dest: 'public',
  runtimeCaching: [
    {
      urlPattern: /^https?:\/\/api\/.*/i,
      handler: 'NetworkFirst',
      options: {
        cacheName: 'api-cache',
      },
    },
  ],
});

🧩 Configuration & Developer Experience

Setup complexity varies significantly. Simpler tools save time initially but may cost you later when requirements grow.

next-offline is the simplest to install. It works well for basic "installable website" needs without complex caching rules.

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

next-optimized-images required specific Webpack loader configuration, which became brittle as Next.js updated its internal Webpack config.

// next-optimized-images: Legacy Webpack config
module.exports = {
  webpack: (config, { isServer }) => {
    // Manual loader injection required
    return config;
  },
};

next-pwa requires a bit more setup but provides a next.config.js structure that scales. It handles the registration of the Service Worker automatically.

// next-pwa: Structured config
module.exports = withPWA({
  pwa: {
    disable: process.env.NODE_ENV === 'development',
    register: true,
    scope: '/',
    sw: 'service-worker.js',
  },
});

πŸš€ Next.js 13+ App Router Compatibility

The shift from Pages Router to App Router (introduced in Next.js 13) impacts plugin compatibility.

next-offline is primarily built for the Pages Router. Using it with App Router often leads to hydration issues or build failures due to changes in how Next.js handles routing and assets.

// next-offline: App Router Risk
// ⚠️ Not officially supported for App Router structure
// May conflict with server components

next-optimized-images is incompatible with the App Router's asset handling. The App Router expects assets to be served via the public folder or imported via native ESM, which conflicts with this plugin's loaders.

// next-optimized-images: App Router Incompatible
// ❌ Do not use with App Router

next-pwa has updated support for Next.js 13+, but it requires specific configuration to work with the new server component architecture. You often need to disable PWA in development and ensure the Service Worker does not intercept Server Component requests incorrectly.

// next-pwa: App Router Config
module.exports = withPWA({
  // Must ensure SW doesn't cache RSC payloads incorrectly
  pwa: {
    disable: process.env.NODE_ENV === 'development',
  },
});

πŸ“Š Summary: Feature Matrix

Featurenext-offlinenext-optimized-imagesnext-pwa
Primary GoalBasic Offline SupportImage Loading/OptimizationFull PWA Suite
Status🟑 Legacy / MaintenanceπŸ”΄ Deprecated🟒 Active
Image Opt❌ Noβœ… Yes (Legacy)
Service Workerβœ… Basic❌ Noβœ… Advanced (Workbox)
App Router❌ Poor Support❌ Incompatible⚠️ Configurable
CustomizationLowMediumHigh

πŸ’‘ The Big Picture

The Next.js ecosystem has matured. What used to require plugins is now often core functionality.

next-optimized-images should be avoided entirely. The native <Image /> component is faster, easier to use, and maintained by the Vercel team. Migrating away from this plugin is a high-priority task for any legacy codebase.

next-offline served a purpose when PWA support was fragmented. Today, it is too limited for complex applications. If you need offline support, you need control over caching strategies, which this package does not provide.

next-pwa is the only viable option among the three for new projects requiring PWA features, specifically on the Pages Router. It gives you the power of Workbox without the boilerplate. However, for Next.js 13+ App Router projects, evaluate if you truly need a third-party plugin. Next.js now supports manifests and service workers more natively, and sometimes a custom Service Worker registration is cleaner than adding a heavy plugin dependency.

Final Recommendation:

  1. Images: Use next/image (Native).
  2. PWA (Pages Router): Use next-pwa.
  3. PWA (App Router): Start with native Next.js PWA support; add next-pwa only if you hit specific Workbox requirements.

How to Choose: next-offline vs next-optimized-images vs next-pwa

  • next-offline:

    Choose next-offline only if you are maintaining a legacy Next.js project (Pages Router) that already depends on it and cannot be migrated. It is not recommended for new projects as it lacks the feature depth and active maintenance of modern alternatives.

  • next-optimized-images:

    Do NOT choose next-optimized-images for any new development. It is effectively deprecated because Next.js now provides native, high-performance image optimization via the next/image component, making this package redundant and potentially conflicting.

  • next-pwa:

    Choose next-pwa if you need a robust, configurable Service Worker strategy for a Next.js Pages Router project or require specific caching behaviors not easily achieved with native tools. For Next.js 13+ App Router, verify compatibility carefully, as native PWA support is improving.

README for next-offline

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 the 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

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

If you're new to workbox, I'd recommend reading this quick guide -- anything inside of worboxOpts 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.

NameTypeDescriptionDefault
generateSwBooleanIf false, next-offline will not generate a service worker and will instead try to modify workboxOpts.swSrctrue
dontAutoRegisterSwBooleanIf 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
devSwSrcStringPath to be registered by next-offline during development. By default next-offline will register a noop during developmentfalse
generateInDevModeBooleanIf true, the service worker will also be generated in development mode. Otherwise the service worker defined in devSwSrc will be used.false
registerSwPrefixStringIf 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
scopeStringThis 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.