While I acknowledge that there may be similar queries out there, I believe mine has a unique angle.
My goal is to send a GET request to the Slack API using an HTTP request.
Here is the code snippet I am working with:
import useSWR from "swr";
const useSlackSearch = (query: string) => {
const token = process.env.NEXT_PUBLIC_SLACK_API_USER_TOKEN;
const myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + token);
const slackURL = `https://slack.com/api/search.messages?query=${query}`;
const fetcher = async (url: string) => {
const response = await fetch(url, {
headers: myHeaders,
}).then((res) => res.json());
return response;
};
const { data, error } = useSWR(slackURL, fetcher, {
revalidateOnFocus: true,
revalidateOnReconnect: true,
});
if (error) {
return console.log(`Failed to load: ${error}`);
} else if (!data) {
return console.log("Loading...");
} else {
console.log(data);
return data;
}
};
export default useSlackSearch;
The setup I am using includes:
- Device: MacBook Air
- OS: macOS
- Browser: Chrome
- From: localhost:3000
- To: Slack API html page ()
Further research led me to understand the intricacies of CORS:
- There is a distinction between simple and preflighted requests
- The Access-Control-Allow-Headers header dictates what headers can be used after a preflight request
- Despite trying to use the Authorization header, it seems to be restricted
For more details on CORS, refer to the following links:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
Confusion arises from Slack API's requirement to specify the token in the Authorization header, despite CORS restrictions.
The challenge lies in specifying the Access-Control-Request-Headers in the preflight header, which seems limited due to browser-JavaScript communication.
Analysis of preflight response from Slack API revealed:
access-control-allow-headers: slack-route, x-slack-version-ts, x-b3-traceid, x-b3-spanid, x-b3-parentspanid, x-b3-sampled, x-b3-flags
Authorization is visibly absent from the allowed headers, indicating a roadblock that needs solving.
https://i.sstatic.net/sAMVa.png
Further investigation unveiled an issue where the browser's preflight request requested the use of Authorization, but the preflight response lacked the necessary value.