In NextJS i have created an API that writes data to my local SQLite db. In dev it works perfectly but on prod i get a 504 Gateway Timeout. My app is self hosted in a VM on a centos with pm2 and nginx. I use cloudflare only as a reverse proxy for extra security. This is where i call the API
useEffect(() => {
const sendVisitorData = async () => {
await fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
};
sendVisitorData();
}, []);
This is my API:
export async function POST(request: Request) {
try {
await new Promise<void>((resolve, reject) => {
db.serialize(() => {
db.run(
'INSERT INTO visitors (visittime, numOfClicks) VALUES (?, ?, ?, ?)',
[visitTime, numOfClicks],
(err: Error | null) => {
if (err) {
logError(err);
reject(err);
} else {
resolve();
}
}
);
});
});
return NextResponse.json({ status: 'Visitor data stored' }, { status: 200 });
} catch (error) {
logError(error);
return NextResponse.json({ error: JSON.stringify(error) }, { status: 500 });
}
}
My nginx only listen for 443 ssl traffic and forwards that toward http://localhost:3000/ (pm2 runs on that port the page is loads correctly only the API not working)
I only allow traffic in from my router that is from Cloudflare’s IPs and only 443 port. In Cloudflare i have disabled cache for doamain.com/api
Franklin777 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.