getFetchClient returns 401 Unauthorized and logs me out from admin panel

Hi,

I am building my custom plugin in the Strapi admin panel. I have created a new plugin via CLI.
When using getFetchClient to get data from an endpoint it returns me a 401 Unauthorized error and logs me out of the admin panel directly. The endpoint I am using is open for public and authenticated. When using axios it returns me the data. But I was testing because with getFetchClient because I want to protect the endpoint and I’ve read that with this method a Bearer token is sent with the headers.

Can someone help me please?

In my plugin HomePage/index.js I have:

import React, { useState, useEffect } from 'react';
import { getFetchClient } from '@strapi/helper-plugin';
import pluginId from '../../pluginId';

const HomePage = () => {

  const { get } = getFetchClient();
  const getGroups = async () => {
    try {
      const response = await get('/api/groups');
      console.log(response.data);
    } catch (error) {
      // Handle error scenario
    }
  };

  useEffect(() => {
    getGroups();
  }, []);

  return (
      <h1>My new plugin</h1>
  );
};

export default HomePage;
2 Likes

This is VERY late, but hopefully this helps the next dev.

I got this same error, and as far as I can tell, the reason is that Strapi has two separate API services, which isn’t documented well anywhere I could find.

There is an “Internal admin API” for plugin-specific or core admin api calls. You can use fetchRequest library because these calls are expected to be used by Admin Users.

There is also a “Content API/ External API” which is the APIs that are auto-generated for each content type as well as anything in the top level src/api folder. These are intended to be used by end users, and have a separate auth JWT token system.

Calling an external API with an Admin User JWT (which is what useFetchClient uses) will result in a 401 because the JWT is invalid for that API’s token service.

As for how to fix this, I have been moving my APIs into a plugin (I just made a “common” plugin), which allows for Admin User access. You could also allow public access to the API in question and use fetch instead of useFetchClient if access isn’t an issue.

1 Like