Skip to content

Commit 15c8720

Browse files
Merge pull request #135 from NikhilSejwal7/master
fix: authenticator example
2 parents cfbbd5d + 7f83058 commit 15c8720

File tree

2 files changed

+18
-25
lines changed

2 files changed

+18
-25
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ ImageKit is a complete media storage, optimization, and transformation solution
1919
* In version 3.0.0, we have deprecated the use of the `authenticationEndpoint` parameter. Instead, the SDK now introduces a new parameter named `authenticator`. This parameter expects an asynchronous function that resolves with an object containing the necessary security parameters i.e `signature`, `token`, and `expire`.
2020
* Now `ref` needs to passed instead of `inputRef` in IKUpload component
2121

22-
Example implementation for `authenticator` using `XMLHttpRequest`.
22+
Example implementation for `authenticator` using `Fetch API`.
2323

2424
``` javascript
2525

tests/test-app/src/App.js

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -42,30 +42,23 @@ function App() {
4242
setIsUploading(false)
4343
};
4444

45-
const authenticator = () => {
46-
return new Promise((resolve, reject) => {
47-
var url = authenticationEndpoint; // Use the full URL with the protocol
48-
49-
// Make the Fetch API request
50-
fetch(url, { method: "GET", mode: "cors" }) // Enable CORS mode
51-
.then((response) => {
52-
if (!response.ok) {
53-
throw new Error(`HTTP error! Status: ${response.status}`);
54-
}
55-
return response.json();
56-
})
57-
.then((body) => {
58-
var obj = {
59-
signature: body.signature,
60-
expire: body.expire,
61-
token: body.token,
62-
};
63-
resolve(obj);
64-
})
65-
.catch((error) => {
66-
reject([error]);
67-
});
68-
});
45+
const authenticator = async () => {
46+
try {
47+
48+
// You can pass headers as well and later validate the request source in the backend, or you can use headers for any other use case.
49+
const response = await fetch(authenticationEndpoint);
50+
51+
if (!response.ok) {
52+
const errorText = await response.text();
53+
throw new Error(`Request failed with status ${response.status}: ${errorText}`);
54+
}
55+
56+
const data = await response.json();
57+
const { signature, expire, token } = data;
58+
return { signature, expire, token };
59+
} catch (error) {
60+
throw new Error(`Authentication request failed: ${error.message}`);
61+
}
6962
};
7063

7164
const onUploadStart = (_) => {

0 commit comments

Comments
 (0)