My setup is a SvelteKit app paired with an Express server (in order to handle sockets). This app has some POST requests which work fine with Vite, but not when I run it with Express. I get the error Cross-site POST form submissions are forbidden with a status code of 403 and a referrer policy "strict-origin-when-cross-origin".
So my question is very similar to this one, but the answers there didn't work for me (except for the insecure option to allow csrf). I also checked the SvelteKit documentation on the node adapter without success.
What I have tried:
- I added the variable
ORIGIN=http://localhost:3000 node build/index.js
to my .env file. I also addeddotenv
as a dependency and addeddotenv.config()
to my server file. But this has no effect. - Setting
csrf: {checkOrigin: false}
insvelte.config.js
fixed the issue, but this is not secure and not recommended. - Running
node -r dotenv/config build
in the terminal. This prints out"Listening on 0.0.0.0:3000"
. But then my express server does not start at all. Perhaps the command needs to be added to thepackage.json
, but I do not know where. There is nonode build
in the file. - When I try to start my Express server with
node -r dotenv/config server.js
and open localhost:3000, I just get Invalid request body (code 400).
It sure is frustrating to setup websockets with SvelteKit, even after reading this blog post.
server.ts:
import express from "express";
import { handler } from "./build/handler.js";
import { attach_sockets } from "./sockets.js";
import dotenv from "dotenv";
dotenv.config();
const PORT = 3000;
const app = express();
const server = app.listen(PORT, () => {
console.log("server is listening on port", PORT);
});
app.use(handler);
attach_sockets(server);