I am trying to proxy all api calls to a service with nextjs. So far this is what I achieved
import { NextApiRequest, NextApiResponse } from "next"
import { getSession } from 'next-auth/client'
import Cookies from 'cookies'
import { apiURL } from 'apps/dashboard/config'
const theProxy = async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession({ req })
const { method, query, headers, body } = req
const cookies = new Cookies(req, res)
let {path, ...params} = query
path = (path as string[]).join("/")
const searchParams = toQueryString(params)
// const authorization = `Bearer ${session.user['remoteToken']}`
let payload = null
if(headers['content-type'] && headers['content-type'].indexOf("multipart/form-data") > -1){
payload = body
} else {
payload = JSON.stringify(body)
}
const options = {
method,
body: method != "GET" && method != "HEAD" ? payload : undefined,
headers: {
'Content-Type': headers['content-type'] || "application/json",
// 'Authorization': authorization,
...(session ? {'cookie': session?.user['cookies']} : {}),
sessionID: cookies.get("sessionID")
}
}
if(headers['content-length']){
options.headers["Content-Length"] = headers['content-length']
}
const response = await fetch(`${apiURL}/${path}?${searchParams}`, options)
try {
const respBody = await response.json()
res.status(response.status).json(respBody)
} catch (error) {
res.status(response.status).end(response.statusText)
}
}
This is working except file upload (multipart). And it looks like uploading but not working properly.
Any suggestions?