ChilTest
ChilTest

Reputation: 511

Next JS API calls with auth0

I have a question about auth0 and next js.

For example, I have the next code (this code works)

//initialprops enables server-side rendering in a page and allows you to do initial data population
ModelsList.getInitialProps = async (ctx) => {
  //this is static token to test from auth0.com
  const accessToken = 'eyJhbG.....'
  //fetching data
  const res = await fetch('http://localhost:7071/api/bo/getModels', {
   headers: {
    Authorization: `Bearer ${accessToken}`
   }
  })
    
  const json = await res.json()
   
  return { data: json }
}

As you can see, I have accessToken variable as a text. It's a problem for me

How can make accessToken dynamic?

Thanks a lot!

P.S please, dont reference to auth0 documentation, I have tried a lot. Provide, please, a real solution/example.

Upvotes: 1

Views: 2145

Answers (1)

alanmynah
alanmynah

Reputation: 221

Ok, so this is what worked for me.

Let's say you've got api.example.com/resources. This where data actually is. You will need to proxy via next's api.

Inside your jsx component, you fetch next's api.

// components/Dashboard.jsx

const API_URL = "api/resources"; 

async function fetcher(url: any) {
  const res = await fetch(url);
  const json = await res.json();
  return json;
}

function Dashboard() {
  const { data, error } = useSWR(API_URL, fetcher);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <div>show your resources here</div>;
}

and now inside the next's api file you can fetch the actual endpoint you need.

// api/resources.js
import {
  getAccessToken,
  getSession,
  withApiAuthRequired,
} from "@auth0/nextjs-auth0";

export default withApiAuthRequired(async function healthcheck(req, res) {
  const session = await getSession(req, res);
  const token = session?.idToken;

  const response = await fetch("https://api.example.com/resources", {
    method: "GET",
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  const data = await response.json();
  res.status(200).json(data);
});

if you get errors, check the jwts you're getting. Audience or scope mismatch errors are usually the main culprits.

Upvotes: 2

Related Questions