This project demonstrates how to integrate a SvelteKit frontend with a Node.js backend using Socket.IO for real-time communication.
SvelteKit Frontend (src/
):
src/routes/+page.svelte
) connects to the WebSocket server running on http://localhost:3000
.eventFromServer
message from the server.invalidate('app:page')
which can be used to trigger data reloading if load
functions depend on it.Node.js Backend (server/index.js
):
handler
from ../build/handler.js
./api/trigger-ws
with enhanced logging and validation./api/trigger-ws
) on the Node.js server. Sending a POST request to this endpoint (e.g., using curl
or Postman) with a JSON body like {"message": "Your update message"}
will cause the server to broadcast that message to all connected SvelteKit clients via the eventFromServer
event.This basic setup can be extended for various real-time features, such as:
Install dependencies:
pnpm install
Build the SvelteKit app:
pnpm build
Start the Node.js server:
node ./server
Alternatively, you can use the npm script:
pnpm start
The server will be running at http://localhost:3000
.
Triggering Updates: Open a separate terminal and send a POST request to the trigger endpoint:
Invoke-RestMethod -Uri http://localhost:3000/api/trigger-ws -Method Post -ContentType 'application/json' -Body '{"message": "Hello from server!"}'
Or using curl
:
curl -X POST -H "Content-Type: application/json" -d '{"message": "Hello from server!"}' http://localhost:3000/api/trigger-ws
You should see the notification appear on the webpage opened at http://localhost:3000
.
Note: Ensure that the WebSocket connection is authenticated by including a valid token in the connection logic.