Garuda Putro
Garuda Putro

Reputation: 1

fetching data form strapi with bearer token using SWR on next js

hi there im using strapi for cms and next js for frontend, and using swr and axios for data fething im trying to fetch data from strapi backend using bearer token , and here is my code

const address = `${process.env.NEXT_PUBLIC_API_URL}/products` 
const auth = `${process.env.NEXT_PUBLIC_API_TOKEN}`

const fetcher = async (url) => await axios.get(url).then((res)=> res.data)
const {data, error} = useSWR(address, auth, fetcher)

console.log(data) 

and when i console.log(data) it's always shown undefined , it's something wrong with my code ? it's any correct way to fetch data with bearer token?

Upvotes: 0

Views: 1682

Answers (2)

Garuda Putro
Garuda Putro

Reputation: 1

i've found the answer thanks anyway

const address = `${process.env.NEXT_PUBLIC_API_URL}/products?populate=*`;
  const auth = `${process.env.NEXT_PUBLIC_API_TOKEN}`;
  async function fetcher(url) {
    const response = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${auth}`,
      },
    });
    return response.data.data;
  }
  const { data, error } = useSWR(address, fetcher);
  let loading = !data && !error;
  console.log(data);

Upvotes: 0

khangnd
khangnd

Reputation: 376

You could pass the bearer token as part of the axios request as below:

const address = `${process.env.NEXT_PUBLIC_API_URL}/products` 
const auth = `${process.env.NEXT_PUBLIC_API_TOKEN}`

const fetcher = async (url) => await axios.get(url, {
  headers: { Authorization: `Bearer ${auth}` }
}).then((res)=> res.data)
const {data, error} = useSWR(address, fetcher)

console.log(data) 

Upvotes: 1

Related Questions