I can't fetch the data from getServerSideProps? #1502
-
Your question I created a route in the api Reproduction // /api/challenge
export default async function challenge(req: NowRequest, res: NowResponse) {
const session = await getSession({ req });
if (!session) {
return res.status(401).json({
error: "You must signin to access this route",
});
}
return res.status(200).json({ ok: true });
} export const api = axios.create({
baseURL: `http://localhost:3000/api/`,
});
export const getServerSideProps: GetServerSideProps = async (context) => {
const response = await api.get('/challenge');
console.log(response);
// Error: 401 You must signin to access this route. But the user is logged in
return {
props: {
level: Number(level ?? 1),
currentExperience: Number(currentExperience ?? 0),
challengesCompleted: Number(challengesCompleted ?? 0),
session: session,
}
}
} export default function Home() {
const { data } = useSWR('/api/challenge');
// it works
console.log(data)
return <h1>Hello World</h1>
} Feedback
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
So there are several problems here. You wrote Also, you shouldn't call a Next.js API route from inside To access the session client-side, you can use the built-in Use the |
Beta Was this translation helpful? Give feedback.
So there are several problems here.
You wrote
/challenge
, but you probably meant/api/challenge
instead.Also, you shouldn't call a Next.js API route from inside
getServerSideProps
, just use the logic directly! (meaning, you can usegetSession directly
insidegetServerSideProps
).To access the session client-side, you can use the built-in
useSession()
hook.Use the
Provider
React Context provider to share (cache) the session betweenuseSession()
calls. You can control how often you want to fetch the session from the API. Check out the options: https://next-auth.js.org/getting-started/client#options