简体   繁体   中英

How to pass something like visitor hits from server (express.js) to next.js?

I've created a simple next.js application and provide it with a backend of express.js, now all I want is whenever someone visits the site a hit should originate on the server and the server should communicate the number of hits back to next.js application. The code of server.js file goes here:

 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); });

as seen here I've set counter variable to zero and want it to be increased whenever a get request is made (so wrote counter++ inside server.get function) but how could I display this number of hits on the route visitor is visiting?

You can use express's res.locals in order to pass the data on the request object.

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);
  });

Then this request object will be available in getInitialProps of the page that is needed.

// some-page.js

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

Page.getInitialProps = ({ req, res }) => {
  if (res) {
    // this means that you are on the server
    return { counter: res.locals.counter };
  }

  return {};
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM