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.