Use proxy for all NIP-95 uploads to avoid CORS and endpoint issues, improve error logging

This commit is contained in:
Nicolas Cantu 2025-12-29 00:30:54 +01:00
parent bafd8ca0bc
commit a4820da2df
2 changed files with 43 additions and 10 deletions

View File

@ -131,12 +131,19 @@ export async function uploadNip95Media(file: File): Promise<MediaRef> {
const error = e instanceof Error ? e : new Error(String(e))
const errorMessage = error.message
// If CORS error, network error, or 405 error, try via proxy
// If CORS error, network error, 405 error, or name resolution error, try via proxy
const isCorsError = errorMessage.includes('CORS') || errorMessage.includes('Failed to fetch')
const isMethodNotAllowed = errorMessage.includes('405') || errorMessage.includes('Method Not Allowed')
if (isCorsError || isMethodNotAllowed) {
const isNameResolutionError = errorMessage.includes('ERR_NAME_NOT_RESOLVED') || errorMessage.includes('getaddrinfo')
const shouldUseProxy = isCorsError || isMethodNotAllowed || isNameResolutionError
if (shouldUseProxy) {
try {
console.log('Trying upload via proxy due to error:', endpoint, isCorsError ? 'CORS' : 'Method Not Allowed')
console.log('Trying upload via proxy due to error:', endpoint, {
CORS: isCorsError,
'Method Not Allowed': isMethodNotAllowed,
'Name Resolution': isNameResolutionError,
})
// Pass endpoint as query parameter to proxy
const proxyUrl = `/api/nip95-upload?endpoint=${encodeURIComponent(endpoint)}`
const url = await tryUploadEndpoint(proxyUrl, formData, true)

View File

@ -62,13 +62,33 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
})
// Forward to target endpoint
const response = await fetch(targetEndpoint, {
let response: Response
try {
response = await fetch(targetEndpoint, {
method: 'POST',
body: formData as unknown as BodyInit,
headers: {
...formData.getHeaders(),
},
})
} catch (fetchError) {
// Clean up temporary file before returning error
try {
fs.unlinkSync(fileField.filepath)
} catch (unlinkError) {
console.error('Error deleting temp file:', unlinkError)
}
const errorMessage = fetchError instanceof Error ? fetchError.message : 'Unknown fetch error'
console.error('NIP-95 proxy fetch error:', {
targetEndpoint,
error: errorMessage,
fileSize: fileField.size,
fileName: fileField.originalFilename,
})
return res.status(500).json({
error: `Failed to connect to upload endpoint: ${errorMessage}`,
})
}
// Clean up temporary file
try {
@ -79,6 +99,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (!response.ok) {
const errorText = await response.text()
console.error('NIP-95 proxy response error:', {
targetEndpoint,
status: response.status,
statusText: response.statusText,
errorText: errorText.substring(0, 200), // Limit log size
})
return res.status(response.status).json({
error: errorText || `Upload failed: ${response.status} ${response.statusText}`,
})