问题描述
如果客户端上当前不存在 ajs_anonymous_id,有人会在 SSR (nextjs) 中设置它吗?
我需要在 Next.Js 中的 SSR 渲染期间“读取” ajs_anonymous_id(细分分析)cookie,但当然也有该 cookie 尚不存在的情况,即...人尚未访问我的之前的站点,因此永远不会去它......但是,因为我需要在 SSR 端......我希望有一个过程我可以在服务器端“设置”它以便我可以使用它,然后拥有它在客户端上也是......所以......
客户访问页面
有 ajs_anonymous_id cookie,很酷,使用它并做一些显示的事情....
没有 ajs_anonymous_id,我播种 ajs_anonymous_id(放一个 cookie)然后做一些显示的事情。
页面加载......我的分析文件(通过容器加载到字体端)看到已经有一个 ajs_anonymous_id cookie,很酷。
任何人都有这样的例子或如何实现它?
解决方法
是的 - 似乎有专门用于此的包和方法。
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 )
}
对于完整示例,我会参考他们的文档: https://segment.com/docs/guides/how-to-guides/collect-pageviews-serverside/
对于 NextJS,我希望你必须摆脱他们的服务器默认实现并构建一个包装器来允许你添加这种类型的中间件。
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}`);
});
});
然后使用 node app/server
希望对您有所帮助!