Skip to content

[feat]: ability to add RequestInit fetch when create Strapi client #107

@Dominic-Preap

Description

@Dominic-Preap

A clear and concise description of what the feature is

It would be nice to be able control fetch option in when create Strapi strapi() and client.collection() to fine grind some configuration on frontend side.

For example

// Can set up on root client
export const client = strapi({
  baseURL: `${env.NEXT_STRAPI_URL}/api`,
  auth: env.NEXT_STRAPI_TOKEN,
  headers:{},

  // Can add next option & timeout
  next: { revalidate: 300, tags: ['api'] },
  signal: AbortSignal.timeout(10000),
});

// Can set up on collection
const posts = client.collection('posts', {
  headers: {},
  next: { revalidate: 300, tags: ['api'] },
  signal: AbortSignal.timeout(10000)
});

Why should this feature be included?

Currently, we can use client.fetch() to set that but it's the opposite purpose. Before the @strapi/client, we already used fetch wrapper already.

The fetch below is working as we expected but lack on typing as we have to create all of those. Now as @strapi/client provide some of the type interfaces, it should be able to customize behaviors on fetch side.

export async function fetchAPI<T>(path: string, urlParamsObject: Params = {}, options = {}) {
  // Build request URL
  const queryString = stringify(urlParamsObject, { addQueryPrefix: true });
  const requestUrl = getStaticURL(`/api${path}${queryString}`);

  // Trigger API call
  const response = await fetch(requestUrl, {
    next: { revalidate: 300, tags: ['api'] },
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${env.NEXT_STRAPI_TOKEN}`
    },
    signal: AbortSignal.timeout(10000),
    ...options
  });

  // Handle response
  if (!response.ok) {
    // eslint-disable-next-line no-console
    console.error(response.statusText);
    throw new Error(`An error occurred please try again`);
  }

  return response.json() as T;
}

Please provide an example for how this would work

N/A

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions