26 lines
760 B
TypeScript
26 lines
760 B
TypeScript
export const getApiBase = () => process.env.NEXT_PUBLIC_API_BASE ?? '/api'
|
|
|
|
export const getToken = () => {
|
|
if (typeof window === 'undefined') return null
|
|
return window.localStorage.getItem('magent_token')
|
|
}
|
|
|
|
export const setToken = (token: string) => {
|
|
if (typeof window === 'undefined') return
|
|
window.localStorage.setItem('magent_token', token)
|
|
}
|
|
|
|
export const clearToken = () => {
|
|
if (typeof window === 'undefined') return
|
|
window.localStorage.removeItem('magent_token')
|
|
}
|
|
|
|
export const authFetch = (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const token = getToken()
|
|
const headers = new Headers(init?.headers || {})
|
|
if (token) {
|
|
headers.set('Authorization', `Bearer ${token}`)
|
|
}
|
|
return fetch(input, { ...init, headers })
|
|
}
|