Skip to content

Use secure cookie with the native fetch credentials: 'include' #1817

Description

@ctjhoa

Hi,
I try Kiota to generate a client usable by my frontend.
However my frontend use secure cookie to connect to my HTTP REST API.
Fetch already have a native option to include secure cookie in the request but Kiota doesn't seems to give a way to configure fetch options out of the box when creating the client.
As it took me some time to figure out the right Kiota configuration, I wanted to document this case here.

import { AnonymousAuthenticationProvider } from '@microsoft/kiota-abstractions';
import { DefaultRequestAdapter } from '@microsoft/kiota-bundle';
import { KiotaClientFactory } from '@microsoft/kiota-http-fetchlibrary';

import { createClient } from './generated/client.js';

// API requires no authentication, so use the anonymous
// authentication provider
const authProvider = new AnonymousAuthenticationProvider();

// Define a custom fetch function to set the 'credentials' option.
// This function wraps the global fetch, but adds our required option.
const customFetch = (url: Parameters<typeof fetch>[0], init?: RequestInit) => fetch(url, {
  ...init,
  credentials: 'include', // 'include' tells the browser to send cookies
});

const httpClient = KiotaClientFactory.create(customFetch);
const adapter = new DefaultRequestAdapter(authProvider, undefined, undefined, httpClient);
export const createHomaioClient = (baseUrl: string) => {
  // Remove trailing slash
  adapter.baseUrl = baseUrl.replace(/\/$/, '');
  return createClient(adapter);
};

It may be valuable to add this case to the documentation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status
    Needs Triage 🔍

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions