无法将数据从自定义预处理器中间件传递到 _app.js

Unable to pass data from custom pre-handler middleware to _app.js

我正在尝试编写一个在 NextJS 处理程序之前运行的中间件,并检查收到的会话 cookie 是否为 valid/untampered。这就是我在 server.js 文件中的连接方式:

server.use('*', preLoadMiddleware);
server.get('*', (req, res) => handle(req, res));

中间件本身尝试设置一个局部变量标记身份验证状态:

import getSessIDFromCookies from '../utils/get-sessid-from-cookies';
import redis from 'redis';
import dotenv from 'dotenv';
dotenv.config();

const preLoadMiddleware = (req, res, next) => {
  const client = redis.createClient(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
  );
  const cookieKeys = Object.keys(req.cookies);
  const sessCookie = getSessIDFromCookies(req);
  client.get(`sess:${sessCookie}`, (err, reply) => {
    if(reply) {
      console.log('SESSION VALID', reply);
      res.locals.authenticated = true;
    }
    else {
      console.log('SESSION NOT VALID');
      res.locals.authenticated = false;
    }
  });
  next();
};

module.exports = preLoadMiddleware;

然后在 _app.js 中,我尝试读取此变量以供进一步决策:

if (ctx.isServer) {
  if(ctx.res) {
    if(ctx.res.locals) {
      console.log('AUTHENTICATED', ctx.res.locals.authenticated);
    }
  }
}

我的问题是,ctx.res.locals.authenticated 总是在 _app.js 中返回 undefined!怎么回事?

我考虑了另一种选择,在我的中间件中设置一个 cookie:

res.cookie('AUTHENTICATED', 'false')

但随后它会抛出一条错误消息:

Can't set headers after they are sent

请帮忙!我应该如何让 _app.js 知道我的中间件在会话 cookie 上的发现?

next() 在中间件中立即被调用。您可能想在回调中调用它。 (client.get 第二个参数)。目前没有等待回调完成。