Next.js + BrowserSync

By candoizo on Jun 14, 2022
Image post 5

In this article, we’ll walk through the steps necessary to install and configure BrowserSync.io with Next.js. We’ll also take a look at how to use BrowserSync.io to improve your development workflow.

BrowserSync is a tool that makes web development faster and easier. It lets you synchronize file changes and browser tabs across multiple devices and resolutions from one screen, saving time during local development.

Requirements

  • A text editor.
  • Node.js installed on your machine.
  • Git installed on your machine.

Steps

  1. Create an example project and add dependencies. This example is my Next.js starter.
git clone https://github.com/candoizo/nextjs-typescript-starter
cd nextjs-typescript-starter
yarn add --dev browser-sync-webpack-plugin
  1. Edit your next.config.js to include the new plugin, Next.js exposes a webpack property but other frameworks could be different.
// next.config.js
import BrowserSyncPlugin from "browser-sync-webpack-plugin";
module.exports = {
 webpack: (config, { dev, isServer }) => {
  const serverSideOrProd = isServer || !dev
  if (!serverSideOrProd)
   config.plugins.push(
    new BrowserSyncPlugin(
     {
      host: '0.0.0.0',
      port: 4000,
      open: false,
      proxy: 'http://localhost:3000/',
     },
     {
      reload: false,
      injectChanges: false,
     },
    ),
   )

  return config
 },
}

Note that we are only injecting the plugin when isServer or dev is defined. This prevents unnecessary inclusion in server-side components which causes many nasty bugs

We disable the reload and injectChanges properties as well because Next.js already comes with Fast Refresh and these would interfere.

  1. Start your server and visit the host + the port field, so in our case it will be available at http://0.0.0.0:4000. Note: 0.0.0.0 implies all addresses on your machine will expose the BrowserSync proxied version of your local development server. Voila!
yarn dev &
firefox http://localhost:4000
fg

For an extra bonus, check out the BrowserSync options at port 3001! CSS guidelines are my favourite.

Conclusion

Webpack has a powerful plugin system and in integrated with many major frameworks. Extensions like BrowserSync can save massive time in the development phase.