S
SolidJS7mo ago
oneiro

Set headers inside createServerAction$()

Hey folks, I am currently trying to explicitely set my content type header to Content-Type: application/json; charset=utf-8 because of some encoding issues. However I don't quite understand how I can do so inside a call of createServerAction$(). I tried to access responseHeaders from useRequest(), however they seem to be always undefined:
const [chartData, submitChartOptions] = createServerAction$(
async (opts: { type: ChartType; options: SubmitChartOptions }) => {
const { responseHeaders } = useRequest();

const result = await generateChartDataByType(opts);

responseHeaders.set("Content-Type", "application/json; charset=utf-8");

return result;
}
);
const [chartData, submitChartOptions] = createServerAction$(
async (opts: { type: ChartType; options: SubmitChartOptions }) => {
const { responseHeaders } = useRequest();

const result = await generateChartDataByType(opts);

responseHeaders.set("Content-Type", "application/json; charset=utf-8");

return result;
}
);
Any idea, what I am doing wrong here? Thanks in advance
1 Reply
Eudrino
Eudrino7mo ago
I believe responseHeaders is read-only here, not sure but using Response should work
const resp = new Response(JSON.stringify(result), { headers: { 'Content-Type': "application/json; charset=utf-8" }});
const resp = new Response(JSON.stringify(result), { headers: { 'Content-Type': "application/json; charset=utf-8" }});
also, if the intended goal is to send json, it's suggested to use the json function from solid-start, using it will simplify the code above to:
const resp = json(result);
return resp;
const resp = json(result);
return resp;