|
| 1 | +export default async function handler(req, res) { |
| 2 | + if (req.method !== 'POST') { |
| 3 | + res.status(405).json({ error: 'Method Not Allowed' }); |
| 4 | + return; |
| 5 | + } |
| 6 | + |
| 7 | + try { |
| 8 | + const { indexUid } = req.query || {}; |
| 9 | + if (!indexUid) { |
| 10 | + res.status(400).json({ error: 'Missing indexUid' }); |
| 11 | + return; |
| 12 | + } |
| 13 | + |
| 14 | + // Read Meilisearch project URL and key. Fallback to values used in Docusaurus config if envs are not set. |
| 15 | + const host = process.env.MEILI_HOST || process.env.NEXT_PUBLIC_MEILI_HOST || 'https://ms-47f23e4f6fb9-30446.fra.meilisearch.io'; |
| 16 | + const apiKey = process.env.MEILI_API_KEY || process.env.NEXT_PUBLIC_MEILI_API_KEY || '45326fd7e6278ec3fc83af7a5c20a2ab4261f8591bd186adf8bf8f962581622b'; |
| 17 | + |
| 18 | + // Forward X-MS-USER-ID if present from the browser request (same-origin; no CORS issue) |
| 19 | + const userId = req.headers['x-ms-user-id']; |
| 20 | + |
| 21 | + const url = new URL(`/indexes/${encodeURIComponent(indexUid)}/search`, host); |
| 22 | + const upstream = await fetch(url.toString(), { |
| 23 | + method: 'POST', |
| 24 | + headers: { |
| 25 | + 'Content-Type': 'application/json', |
| 26 | + 'Authorization': `Bearer ${apiKey}`, |
| 27 | + 'X-Meilisearch-Client': req.headers['x-meilisearch-client'] || 'StrapiDocs Proxy', |
| 28 | + ...(userId ? { 'X-MS-USER-ID': String(userId) } : {}), |
| 29 | + }, |
| 30 | + body: JSON.stringify(req.body || {}), |
| 31 | + }); |
| 32 | + |
| 33 | + const body = await upstream.text(); |
| 34 | + // Pass through status and JSON body |
| 35 | + res.status(upstream.status); |
| 36 | + try { |
| 37 | + res.setHeader('Content-Type', 'application/json'); |
| 38 | + res.send(body); |
| 39 | + } catch { |
| 40 | + res.json({ error: 'Invalid upstream response' }); |
| 41 | + } |
| 42 | + } catch (e) { |
| 43 | + res.status(500).json({ error: e.message || 'Proxy error' }); |
| 44 | + } |
| 45 | +} |
| 46 | + |
0 commit comments