nicer00ster
nicer00ster

Reputation: 63

Confused on service worker with NextJS & Express

I've spent the last two days (literally) trying to get a service worker running on my NextJS application that runs Express as the server. The repo where I'm hosting all the code is https://github.com/nicer00ster/nicer00ster-portfolio I'm just looking for a hint as to where I'm going wrong. The reason I'm using Express is to send mail, and all the examples that use next-offline or any other server configuration uses the http plugin.

I've been working on this portfolio for about 2 months now and I really want to get my Lighthouse score up before I decide to push it live. Any direction would be of great value. Thank you!

Upvotes: 1

Views: 2191

Answers (3)

Phillip Boateng
Phillip Boateng

Reputation: 1121

So this week I was also trying to set up a project that was “lighthouse verified” lets say.

Next have a really good directory of examples. The particular example I followed that helped me set this up was next.js/examples/with-sw-precache

It's a similar setup to yours only using the SWPrecacheWebpackPlugin with a standard setup

The step that seems to be missing, which may be the problem, is that your not registering your service worker. In your index file, you could register the service-worker in the componentDidMount Lifecycle.

import React from 'react'

export default class extends React.PureComponent {
  componentDidMount() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker
        .register('/service-worker.js')
        .then(registration => {
          console.log('service worker registration successful')
        })
        .catch(err => {
          console.warn('service worker registration failed', err.message)
        })
    }
  }
  render() {
    return <p>Check the console for the Service Worker registration status.</p>
  }
}

Upvotes: 0

nicer00ster
nicer00ster

Reputation: 63

Finally figured this out, ended up ditching Express and just handling the body of the response for emails through Node:

const { headers, method, url } = req;
let body = [];
req.on('error', (err) => {
  console.error(err);
}).on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
})

Then used the same nodemailer sendTransport function I had already been using. Service worker is running as well as mail going out! =D

Upvotes: 1

tic
tic

Reputation: 147

I don't have enough rep to leave a comment, but...

The repl.it links you linked to are Native Browser Javascript repls, which doesn't run node, and by extension, express. You'll need to use a nodeJS repl or, if you prefer, use our express template.

Upvotes: 0

Related Questions