Fix: Use window.location.origin for API base URL in browser
treaty from @elysiajs/eden doesn't support relative URLs like '/' This caused 'ERR_NAME_NOT_RESOLVED' when trying to access 'https://api/fileStorage/create' Solution: - Client-side: Use window.location.origin (e.g., https://desa-darmasaba-stg.wibudev.com) - Server-side dev: Use localhost:3000 - Server-side prod: Use NEXT_PUBLIC_BASE_URL env var This ensures the API calls use the correct domain in all environments. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
@@ -1,10 +1,25 @@
|
||||
import { AppServer } from '@/app/api/[[...slugs]]/route'
|
||||
import { treaty } from '@elysiajs/eden'
|
||||
|
||||
// Use relative URL '/' for better deployment flexibility
|
||||
// This allows the API to work correctly in both development and staging/production
|
||||
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || '/'
|
||||
// Determine the base URL based on environment
|
||||
// treaty requires a full URL, cannot use relative paths like '/'
|
||||
const getBaseUrl = () => {
|
||||
// Development (server-side)
|
||||
if (process.env.NODE_ENV === 'development' && typeof window === 'undefined') {
|
||||
return process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'
|
||||
}
|
||||
|
||||
// Client-side (browser) - use current window origin
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
// Production/Staging server-side - use environment variable or default
|
||||
return process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'
|
||||
}
|
||||
|
||||
const BASE_URL = getBaseUrl()
|
||||
|
||||
const ApiFetch = treaty<AppServer>(BASE_URL)
|
||||
|
||||
export default ApiFetch
|
||||
export default ApiFetch
|
||||
|
||||
Reference in New Issue
Block a user