Making Non-Browser Requests to Avoid CORS Issues cover image

Making Non-Browser Requests to Avoid CORS Issues

When integrating systems into a launcher, CORS (Cross-Origin Resource Sharing) issues can arise. These occur when a backend service isn’t configured to handle requests from a browser environment, such as those made within the PatchKit Launcher Theme context. Fortunately, the PatchKit Launcher SDK provides a simple solution: the `call

callNodeFetch function. This utility allows you to bypass CORS restrictions by making requests directly from Electron’s Node.js context instead of the browser environment.

In this guide, we’ll explore how to use callNodeFetch, its benefits, and how to adapt your existing fetch calls to avoid CORS issues effectively.

Why Avoid Browser-Based Requests?

Browser-based requests are subject to CORS policies that enforce security by restricting cross-origin requests. If a backend isn’t configured for browser access, requests may fail unless headers like Access-Control-Allow-Origin are correctly set. Configuring this for every backend can be impractical or impossible, especially with third-party services.

How callNodeFetch Solves the Problem

The callNodeFetch function executes HTTP requests directly from the Node.js context in Electron, avoiding browser-related CORS policies altogether. Its interface mimics the standard fetch API, making it straightforward to transition from browser-based requests. However, keep in mind:

  • No Browser Headers: Requests made with callNodeFetch do not include browser-specific headers like cookies or the User-Agent header.
  • Node.js Environment: These requests are isolated from browser-based security contexts.

Step-by-Step Guide: Replacing fetch with callNodeFetch

Here’s how to refactor your code:

1. Original Browser-Based fetch Request

In a typical scenario, a fetch request from the browser might look like this:

try {
  const response = await fetch(
    `https://backend-without-cors-config.com/api/path`,
    {
      method: `POST`,
      headers: {
        authorization: `Bearer ${accessToken}`,
      },
    },
  );

  if (!response.ok) {
    console.warn(`Response Status Code: ${response.status}`);
  } else {
    console.log(`Response Status Code: ${response.status}`);
  }
} catch (error) {
  console.error(error);
}

2. Refactored Request Using callNodeFetch

To avoid CORS issues, replace fetch with callNodeFetch:

const { response, error } = await callNodeFetch({
  nodeFetchArgs: {
    input: `https://backend-without-cors-config.com/api/path`,
    init: {
      method: `POST`,
      headers: {
        authorization: `Bearer ${accessToken}`,
      },
    },
  },
});

if (response !== undefined) {
  if (!response.ok) {
    console.warn(`Response Status Code: ${response.status}`);
  } else {
    console.log(`Response Status Code: ${response.status}`);
  }
} else {
  console.error(error);
}

Key Changes

  1. Input Structure: callNodeFetch requires a single argument with the nodeFetchArgs property, containing:
    • input: The URL for the request.
    • init: An object resembling fetch options (e.g., method, headers).
  2. Error Handling: callNodeFetch separates response and error, simplifying error management.

Practical Tips for Using callNodeFetch

  • Authentication: Ensure headers like Authorization are explicitly set in the init object, as browser cookies are not automatically included.
  • Response Validation: Always check if response is undefined to differentiate between network errors and unsuccessful HTTP status codes.
  • Environment-Specific Logic: Use callNodeFetch only in environments where Node.js is accessible, such as the Electron-based launcher.

Conclusion

The callNodeFetch function is a powerful tool for overcoming CORS issues when integrating backend services into the PatchKit Launcher. By bypassing browser-based restrictions, it simplifies communication with backends that lack CORS configurations. Refactoring your fetch calls to callNodeFetch ensures smoother integration and more robust functionality within your launcher.

Ready to enhance your integration? Try replacing your fetch calls with callNodeFetch today! For more details, refer to the PatchKit Launcher SDK documentation. Stay tuned for more detailed guides on each aspect of PatchKit integration!