What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js code below:

const express = require("express");
const next = require("next");

var counter = 0;

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });

const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    server.get("*", (req, res) => {
      counter++;
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

In this code snippet, I’ve initialized the counter variable to zero and set it to increment each time a GET request is made (using counter++ inside the server.get function). Now, the challenge lies in figuring out how to display this hit count on the specific route that the visitor is accessing.

Answer №1

To transmit data on the request object, you can make use of express's res.locals.

app
  .prepare()
  .then(() => {
    const server = express();

    server.get('*', (req, res) => {
      counter++;
      res.locals.counter = counter;
      //----^
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

The request object will then be accessible in the getInitialProps function of the required page.

// some-page.js

const Page = ({ counter }) => <div>{counter}</div>;

Page.getInitialProps = ({ req, res }) => {
  if (res) {
    // Indicates that the code is running on the server
    return { counter: res.locals.counter };
  }

  return {};
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

How to trigger a function to run only once in React when the page is accessed or refreshed

I'm currently developing a search feature using Algolia search functionality. Users can input a search term from another site, be redirected to the search page, and have the search executed automatically. Once on the search page, users must utilize t ...

Troubleshooting: Next.js application deployment on Azure Web App encountering file discrepancies

I'm currently facing an issue while attempting to deploy a next.js (with typescript) application on Azure using Bitbucket pipelines. As part of my pipeline process, I build the next.js app with the following build configuration: // next.config.js /** ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...

Arranging elements in a list according to their position on the canvas using AngularJS

I am currently working on drawing rectangles on an html5 canvas using the JSON format provided below. My goal is to sort the array based on the x and y locations of each element. { "obj0": { "outerRects": [ { "outerRectRoi": { "x1": 0, " ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Updating a d3.js force-directed graph may retain previous JSON data during the reloading process

Having a d3.js force-directed graph that pulls data from a JSON feed, I encounter an issue when clicking on a node. Although the updated JSON is correct, the displayed graph does not reflect this new data. It seems like the graph is retaining previous info ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

Why is it that the window object in JavaScript lacks this key, while the console has it?

let myFunction = function declareFunc() { console.log(this); // window console.log(this.declareFunc); // undefined console.log(declareFunc); // function body } console.log(this) // window myFunction(); I understand that the this keyword in a functio ...

"Encountered an error: User.findAll function cannot be found

Here is the content of my user.js file: var sequelize = require('sequelize'); var bcrypt = require('bcrypt'); module.exports = function(sequelize, DataTypes) { const User = sequelize.define('users', { user_id: { ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

What is the proper way to utilize the toISOString() function in JavaScript?

My current code uses currentDate.toISOString() to output the date in this format: "2013-01-15T12:08:54.135Z". However, I actually need the date to be formatted like this: "2013-01-15T12:08:54-06:00". The "-06:00" represents the timezone. ...

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Nodejs App cannot be started locally due to a directory import issue

My journey to deploy my app on Heroku has hit a roadblock. The import statements, like import cors from 'cors', are causing the app to fail in production with the "Cannot Load ES6 Modules in Common JS" error. Interestingly, everything runs smooth ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

What is the method for retrieving information from a mongoose query function's callback?

For my inaugural endeavor with mongodb, I am creating an URL shortener using express and mongoose. I am encountering difficulties in retrieving data from the callback function. The two schemas that I have are: //Store the url, corresponding short url and ...