1. 13
    Set Dynamic Auth Header for Apollo Client using Next.js getServerSideProps
    3m 3s

Set Dynamic Auth Header for Apollo Client using Next.js getServerSideProps

Shadid Haque
InstructorShadid Haque
Share this video with your friends

Social Share Links

Send Tweet

To make an authenticated request, we will need to get logged in users auth tokens from Auth0. Auth0 exposes a getAccessToken function that we can use in Next.js getServerSideProps to fetch the user token. It's important to note that this function can only be used server side. We'll pass that token into the page we need to send authed requests.

To enable Apollo Client to set the headers we'll extend the client so that allows us to pass in auth tokens and sets the client context. We will then destructure the client from our useMutation hook and set the context to include the user token.

Shadid Haque: [0:00] We're going to go back to manage-shops.tsx file. Here, we're going to import getAccessToken from auth0. The getAccessToken function can only be called from the server-side of Next.Js. We'll create the getServerSideProps function.

[0:24] We are going to call the getAccessToken, pass in the context request and response. We will return the accessToken as props. Back in our page component, we can pass this accessToken to our NewShopForm component. In our newShop component, let's define the accessToken prop as a string type.

[0:50] Next, we're going to head back to our gqlClient.ts file. Here, we're going to create our curried function. Now, this function takes in a token string as a parameter. Then we call the setContext from Apollo, and then we set our header authorization based on the passed-in token.

[1:23] Let's export this function as we want to use it in our component. Notice that this function is pretty much identical to the authLink function, except in our setAuthToken function we pass in a token and this token get set as our authorization header. Let's go ahead and also export the httpLink function. We're going to be needing this in our component as well.

[1:50] Next, let's go back to our NewShopForm. Here, we're going to import httpLink and setAuthToken from gqlClient. Then we go down here, and we destructure the client from our useMutation hook.

[2:10] We're going to call the setLink on client. We're going to pass in the setAuthToken, and we're going to pass in the accessToken from auth0 and concat this with httpLink.

[2:29] This configuration will make it so that we are using the accessToken from auth0 in our Apollo client headers. Now, here when we were doing createNewShop, this is actually going to use the accessToken that we passed in from auth0.

[2:43] Now, let's go ahead and try to create a new shop. This time, you'll see that we can successfully create a new shop. Now, if we go inspect our Network tab, you'll see that in the headers we're now passing in the auth0 token.