google-analyticsnext.jssegment-analytics

Setting Segment ajs_anonymous_id from SSR on client if user doesn't have cookie with Next.js App?


Anyone set the ajs_anonymous_id in SSR (Next.js) if it doesn't currently exist on client?

I have a need to "read" the ajs_anonymous_id (Segment analytics) cookie during a SSR rendering in Next.Js, but of course there are instances when that cookie does not exist yet ie...person hasn't visited my site before and thus never go it... BUT, since i need in SSR side..... I was hoping there is a process I can "set it" on the server side so that I can use it, THEN have it on the client too... so..

Client visits page

Has ajs_anonymous_id cookie, cool, use it and do some display things....

Does not have ajs_anonymous_id, I seed the ajs_anonymous_id (drop a cookie) and then do some display things.

Pages loads.. My analytics file (that loads on the font end thru a containe) sees there is an already ajs_anonymous_id cookie, cool.

Anyone have an example of this or how to achieve it?


Solution

  • yeah - there seems to be a package and method just for this.

    
    import Analytics from 'analytics-node'
    
    // if no anonymousId, send a randomly generated one
      // otherwise grab existing to include in call to segment
      let anonymousId
      if (cookies.ajs_anonymous_id) {
        anonymousId = cookies.ajs_anonymous_id
      } else {
        anonymousId = = uuid.v4()
        res.cookie('ajs_anonymous_id', anonymousId )
      }
    

    for the full example, i'd refer to their docs: https://segment.com/docs/guides/how-to-guides/collect-pageviews-serverside/

    For NextJS, I expect you have to move away from their server default implementation and build a wrapper to allow you to add this type of middleware.

    const express = require('express');
    const bodyParser = require('body-parser');
    const next = require('next');
    
    const host = process.env.LOCAL_ADDRESS || '0.0.0.0';
    const port = parseInt(process.env.NODE_PORT, 10) || 3000;
    const dev = process.env.NODE_ENV !== 'production';
    const app = next({ dev, dir: 'app' });
    const handle = app.getRequestHandler();
    
    app.prepare().then(() => {
        const server = express();
    
        server.use(bodyParser.urlencoded({ extended: false }));
        server.set('trust proxy', true);
    
        server.use(customMiddleware);
    
        server.all('*', (req, ...args) => {
            // Log the request only if we need to (we don't log all static asset requests)
            if (req.log) {
                req.log.info('incoming request');
            }
    
            return handle(req, ...args);
        });
    
        server.listen(port, host, (err) => {
            if (err) throw err;
            console.log(`> Ready on http://${host}:${port}`);
        });
    });
    

    then start the app with node app/server

    Hope that helps to get you started!