Nuxt + Web Workers, logout after idle (part 1)

paramo

Paramo

Posted on May 22, 2020

Nuxt + Web Workers, logout after idle (part 1)

Para la versión en español ve a mi blog

In this post we are going to see how to logout a user after idle using Nuxt and Web Workers. I found out is a long process so im gonna keep it simple and well explained so everybody can follow along. Due to its extension I'm going to divide it into different sections.

In this section we are going to:

  1. Install and configure everything needed to use web workers with Nuxt.
  2. Code our very first worker
  3. Execute our worker

I'm not going to explain what web workers are, but we are going to see how they work.

Are you ready? Here we go!

Installation and configuration

First we are going to install worker-loader this will help us to make webpack register our worker

Install with yarn:

yarn add worker-loader
Enter fullscreen mode Exit fullscreen mode

Next we are goint to nuxt.config.js and add the following code over build

build: {
 extend (config, ctx) {
  if (ctx.isClient) {
   config.module.rules.push({
    test: /\.worker\.js$/,
    loader: 'worker-loader',
    exclude: /(node_modules)/
   })
  }
 }
}
Enter fullscreen mode Exit fullscreen mode

With this we are telling webpack to get all the files with extension .worker.js and load them through worker-loader

All the files that serve as workers must have .worker.js extension*

Coding our very first worker

Let's add a new file under plugins directory (the name is up to you) and add the following.

import  SessionWorker  from  '~/assets/js/session.worker.js'

export  default (context, inject) => {
  inject('worker', {
   createWorker () {
   return  new  SessionWorker()
  }
 })
}
Enter fullscreen mode Exit fullscreen mode

and then we register it in nuxt.config.js

plugins: [
 { src: '~/plugins/web-worker.js', ssr: false } 
 /* Important ssr: false 
 cause the workers wont work server side, just client*/
],
Enter fullscreen mode Exit fullscreen mode

At the moment the compilation will fail because we have not created our file session.worker.js but patience, we are going to that.

Here we are basically giving the necessary instruction to create our worker. If you have doubts about plugins head to the documentation, its explained very simple.

Now we will create a folder and a file inside assets (assets -> js -> session.worker.js)

It is important that the new file is called in the same way as the one we import in our plugin, and it is on the same path.
And add:

self.addEventListener('message', (event) => {
 console.log('[WORKER] worker con data: ', event.data)
})
Enter fullscreen mode Exit fullscreen mode

What is this?
self references the worker itself
message it is the first parameter that the function receives and should not say otherwise.

If its different than message It wont work

The event parameter is the one it receives when worker is called (we'll get to that)

So what my worker will do? just print to console the received message

But, how? Lets see.

Executing our worker

Lets head to pages -> index (you can actually run it anywhere, I chose in that specific place because it is the first contact of the application) and we add the following:

created: function () {
 if (process.browser) { // Remember workers just work in client?
  const worker = this.$worker.createWorker() // Instruction assigned in plugin
  worker.addEventListener('message', this.workerResponseHandler)
  worker.postMessage('Message sent to worker')
 }
},
methods: {
 workerResponseHandler: function (event) {
  console.log('[WORKER REPONSE]', event.data)
 }
}
Enter fullscreen mode Exit fullscreen mode

What did we just see?
const worker = this.$worker.createWorker() We are creating the worker variable to start it.
worker.addEventListener('message', this.workerResponseHandler) We are creating the event by passing two parameters:

  • message this must keep it's name, otherwise wont work
  • this.workerResponseHandler function that handles worker response.

worker.postMessage('Message sent to worker') We send a message to our worker so it can be printed in console

Lastly:
workerResponseHandler print the worker response.

Its done! It is all for our first part, an apology if the explanation is very extensive, however it is a complicated process and I wanted it to be as clear as possible.

What we saw in this tutorial?

  1. Install and configure everything needed to use web workers with Nuxt.
  2. Code our very first worker
  3. Execute our worker

Stay with me to see the next steps to logout a user after X time of inactivity.

Any questions or comments you have, with pleasure you can find me on twitter as @c3ppeu

Greetings!

💖 💪 🙅 🚩
paramo
Paramo

Posted on May 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related