Retrieving Access Token with getServerSideProps

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.

Hi @martinassaid,

Yes, that is an appropriate approach :clap:.

I see that you are calling the getSession method to check if there is a valid session before getting the access token and returning it as props.

And if no valid session exists, the function returns an empty object as props. This makes sense and the overall code is appropriate for fetching the user session and access token using getServerSideProps.

I will also share this auth0-next.js reference of an example using getServerSideProps which you may find useful.

Let me know if you have any questions.

Thanks,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.