NextAuth.js getServerSession 返回 null,即使用户已登录。

huangapple go评论63阅读模式
英文:

NextAuth.js getServerSession return null even after user is sign in

问题

I try to implement protected route in Next.js using NextAuth.js

inside my API i use getServerSession method to fetch login user.
Now i use it inside getServerSideProps getServerSession works for first time but when i use fetched session and make a API call it return a nell and get a 401 error.

But when i make the same api call in browser it fetched session as you see in screenshot below
fetched session from api

Here is my code..

//My frontend code
export async function getServerSideProps(context) {
  const session = await getServerSession(context.req, context.res, authOptions); //It works properly

  if (session) {
    try {
      const { data } = await Axios.get(`/api/profile/${session.user.uid}`); //But can't able to fetch session from REST API it return a status code 401
      return {
        props: {
          user: data,
        },
      };
    } catch (error) {}
  }

  return {
    redirect: {
      destination: "/api/auth/signin",
      permanent: false,
    },
  };
}

//Backend code
export default async (req, res) => {
  const session = await getServerSession(req, res, authOptions);

  if (!session)
    return res.status(401).json({
      error: "unauthenticated user is not allowed.",
    });

  try {
    await connectToDB();
  } catch (error) {
    return res
      .status(500)
      .json({ error: "server can't able to connect to DB." });
  }

  const {
    method,
    query: { id },
  } = req;

  switch (method) {
    case "GET":
      try {
        const user = await User.findById(id);
        if (user) res.status(200).json(user);
        else res.status(500).json({ error: "No user found for the given id." });
      } catch (error) {
        res.status(500).json({
          error: error.message,
        });
      }
      break;
    default:
      res.status(501).json({ error: "Invalid Request." });
  }
};

Here what i want is first getServerSession fetch session first time and use that session data to make a API call. (which work correctly)
But after fetched session i make a API call and inside my API call i again check if user is login (to protect API route also) but it return 401 error.

Now if i made that API call using browser it fetched my session.

英文:

I try to implement protected route in Next.js using NextAuth.js

inside my API i use getServerSession method to fetch login user.
Now i use it inside getServerSideProps getServerSession works for first time but when i use fetched session and make a API call it return a nell and get a 401 error.

But when i make the same api call in browser it fetched session as you see in screenshot below
fetched session from api

Here is my code..

//My frontend code
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions); //It works properly
if (session) {
try {
const { data } = await Axios.get(`/api/profile/${session.user.uid}`); //But can't able to fetch session from REST API it return a status code 401
return {
props: {
user: data,
},
};
} catch (error) {}
}
return {
redirect: {
destination: "/api/auth/signin",
permanent: false,
},
};
}
//Backend code
export default async (req, res) => {
const session = await getServerSession(req, res, authOptions);
if (!session)
return res.status(401).json({
error: "unauthenticated user is not allowed.",
});
try {
await connectToDB();
} catch (error) {
return res
.status(500)
.json({ error: "server can't able to connect to DB." });
}
const {
method,
query: { id },
} = req;
switch (method) {
case "GET":
try {
const user = await User.findById(id);
if (user) res.status(200).json(user);
else res.status(500).json({ error: "No user found for the given id." });
} catch (error) {
res.status(500).json({
error: error.message,
});
}
break;
default:
res.status(501).json({ error: "Invalid Request." });
}
};

Here what i want is first getServerSession fetch session first time and use that session data to make a API call. (which work correctly)
But after fetched session i make a API call and inside my API call i again check if user is login (to protect API route also) but it return 401 error.

Now if i made that API call using browser it fetched my session.

答案1

得分: 1

In Next.js 在使用 getServerSideProps 时,它接受一个 context 参数。
在执行 API 请求时,需要手动添加一个 cookie 头部。

像这样:

const response = await Axios.get(`/api/profile/${uid}`, {
    headers: {
        Cookie: context.req.headers.cookie,
    },
});
英文:

In Next.js when working with getServerSideProps it accepts a context parameter.
You have to manually add a cookie header when doing an API request.

Like This:

const response = await Axios.get(`/api/profile/${uid}`, {
    headers: {
        Cookie: context.req.headers.cookie,
    },
}); 

huangapple
  • 本文由 发表于 2023年5月21日 16:04:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定