Is the following approach to obtaining an Access Token using getServerSideProps appropriate?
The approach works fine but most examples I have seen don’t check if there is a session first. If I strip out the session check then getAccessToken throws an error if there is no valid session. That then requires some awkward error handling with try/catch. Is this the right behaviour for getAccessToken? I assumed it would return undefined as it’s not really an error, there just isn’t a session.
// pages/index.tsx
import { getAccessToken, getSession } from "@auth0/nextjs-auth0";
export default function Home({ accessToken }) {
return (
<>
<button
onClick={async () => {
await fetch("http://localhost:5500/api/v1/example", {
headers: {
Authorization: `Bearer ${accessToken}}`,
},
});
}}
>
Test Button
</button>
</>
);
}
export async function getServerSideProps(ctx) {
const session = await getSession(ctx.req, ctx.res);
if (session) {
const { accessToken } = await getAccessToken(ctx.req, ctx.res);
return { props: { accessToken } };
}
return { props: {} };
}
Many thanks for your thoughts / comments.