无法在nextjs中的getServerSideProps中访问会话或req.user

时间:2020-06-21 03:17:21

标签: node.js session passport.js next.js

我需要基于userId来获取数据,但是要使用SSR并利用SSR功能,如何访问在SSR函数userId中成功登录后获得的getServerSideProps由NextJS提供。我现在有以下实现。

用户登录后将被重定向到pages/index.js, 这是pages/index.js

import { useUser } from '../libs/hooks';
import { client } from '../middlewares/database';
import Home from './Home';
import Landing from './Landing';

const App = ({ data }) => {
  
    const [user] = useUser();
    /* I have the user details here and I have a hook for getting user details,
but this is the client-side */
    return user?<Home data={data} />:<Landing />
}

export async function getServerSideProps(context) {
    const userId = context.req.headers.userId;
    // userId is undefined here, I need the userId here
    if (!client.isConnected()) await client.connect();

    const db = client.db(process.env.DB_NAME);
    const response = await db.collection("data").find({ userId });
    
    return { props: { data: response } }
}

export default App;

我正在使用passport.jsnext-session来认证用户并创建会话sid,该会话在所有功能中都可用。如果我可以将userId存储在会话中,那也会有所帮助。

这是我的服务器中间件。

import nextConnect from "next-connect";
import passport from "../libs/passport";
import database from "./database";
import session from "./session";

const middleware = nextConnect();

middleware
  .use(database)
  .use(session)
  .use(passport.initialize())
  .use(passport.session());

export default middleware;

这是登录身份验证文件的外观; auth.js

import nextConnect from 'next-connect';
import { session } from 'next-session';
import { extractUser } from '../../libs/api-helpers';
import passport from '../../libs/passport';
import middleware from '../../middlewares/middleware';

const handler = nextConnect();
handler.use(middleware);

handler.post(passport.authenticate('local'), async (req, res) => {

  res.json({ user: extractUser(req) });
});

我可以使用cookie方法或会话方法。在这种情况下,如何在这里实现?

2 个答案:

答案 0 :(得分:1)

someMiddlewares.apply 已被弃用。请使用someMiddlewares.run

await someMiddleswares.apply(req, res)

https://www.npmjs.com/package/next-connect#runreq-res

答案 1 :(得分:0)

定义并导出您的中间件:

import nextConnect from 'next-connect'

const middleware = nextConnect()

middleware.use(session)
middleware.use(passport.initialize())
middleware.use(passport.session())

export default middleware

使用nextConnect apply方法来应用所有中间件:

export async function getServerSideProps({ req, res }) {
  await middlewares.apply(req, res)
  console.log(req.user._id) // the user is available now!