Home > Blockchain >  How to use POST api token to use third party APIs in nextjs
How to use POST api token to use third party APIs in nextjs

Time:10-08

I need to POST to a third party api route to receive an access token to be authorized to fetch data from their endpoints, but I'm not sure how to use the token. They are using Swagger:

export default async function() {
  const res = await fetch('url', {
    method:'POST',
    headers: {
      accept: 'application/json'
    }
  });
  const data = await res.json()
  console.log(data)
}

I get in response:

{
  access_token: 'my token...',
  ...
}

But I'm not sure how I'd use this response to authorize fetching data. Do I need to pass the token to the headers in the fetch?

export async function getStaticProps() {
  const res = await fetch( `url`, {
    headers: {
      accept: 'application/json',
    }
  });
  const data = await JSON.stringify(res);

  return {
     props: {
        items: data
     },
  };
}

I can't seem to find much info on this, or I'm just searching for the wrong things. I'm not sure if I'm understanding this correctly

CodePudding user response:

Likely you'll need to send that token in an Authorization header with the request, something like this:

  const res = await fetch(`url`, {
    headers: {
      accept: 'application/json',
      Authorization: `Bearer ${token}`,
    }
  });
  const json = await res.json()
  const data = JSON.stringify(json);

The API docs should be able to tell you specifics though, if you're still having issues please post the API docs if they're public!

  • Related