Hey there!
I know its been some time since this was posted, but i want to confirm that i now have a working setup for this and im gonna share my code so others dont have to search for HOURS just like me on how to properly do it.
I used Vue Ionic
First off: @twestrick, your answer was my guiding light tbh! So thanks for that!
I ended up using the native capacitor cookie plugin: Here
And Capacitor Http: Here
And just wrote up a api service to use everywhere!
Here is the code, have fun! ![:smiley: :smiley:]()
import { CapacitorHttp as Http } from '@capacitor/core';
// API key
const BASE_URL: string = import.meta.env.VITE_APP_API_BASE_URL;
interface ApiResponse<T> {
data: T;
status: number;
}
interface ApiError {
statusCode: number;
message: string;
}
// Centralized Error Handler
const handleError = (error: any): ApiError => {
return {
statusCode: error.status || 500,
message: error.message || 'An unexpected error occurred',
};
};
export const apiService = {
async get<T>(url: string, options: object = {}): Promise<T> {
try {
const response: ApiResponse<T> = await Http.get({
url: `${BASE_URL}${url}`,
headers: {
'Content-Type': 'application/json',
'x-api-key': "YOUR API KEY",
},
connectTimeout: 5000,
readTimeout: 5000,
webFetchExtra: { credentials: 'include' },
...options,
});
return response.data;
} catch (error) {
throw handleError(error);
}
},
async post<T>(url: string, body: object | null = null, options: object = {}): Promise<T> {
try {
const response: ApiResponse<T> = await Http.post({
url: `${BASE_URL}${url}`,
headers: {
'Content-Type': 'application/json',
'x-api-key': "YOUR API KEY",
},
data: body,
connectTimeout: 5000,
readTimeout: 5000,
webFetchExtra: { credentials: 'include' },
...options,
});
return response.data;
} catch (error) {
throw handleError(error);
}
},
async put<T>(url: string, body: object, options: object = {}): Promise<T> {
try {
const response: ApiResponse<T> = await Http.put({
url: `${BASE_URL}${url}`,
headers: {
'Content-Type': 'application/json',
'x-api-key': "YOUR API KEY",
},
data: body,
connectTimeout: 5000,
readTimeout: 5000,
webFetchExtra: { credentials: 'include' },
...options,
});
return response.data;
} catch (error) {
throw handleError(error);
}
},
async delete<T>(url: string, options: object = {}): Promise<T> {
try {
const response: ApiResponse<T> = await Http.delete({
url: `${BASE_URL}${url}`,
headers: {
'Content-Type': 'application/json',
'x-api-key': "YOUR API KEY",
},
connectTimeout: 5000,
readTimeout: 5000,
webFetchExtra: { credentials: 'include' },
...options,
});
return response.data;
} catch (error) {
throw handleError(error);
}
},
};
PS: Make sure your cookies handle the domain property correctly aswell ;D
→ Oh and also: adjust the timeouts depending on data-load and your own estimate!