Server setup
Setting up
Install package
npm install streamthing
Environment variables
.env
SERVER_PASSWORD=abc123
SERVER_REGION=us3
SERVER_ID=123987
Server setup
If the framework you use doesn't give you preconfigured route handlers like Next JS, you'll have to create your own server. The way we recommend you do this is by using Fastify.
index.ts
import Fastify from "fastify";
import { createServerStream, createToken } from "streamthing";
const fastify = Fastify();
const PORT = process.env.PORT || 5000;
fastify.get("/get-streamthing-token", async (request, reply) => {
// Some sort of auth
const token = await createToken({
id: process.env.SERVER_ID,
channel: "main",
password: process.env.SERVER_PASSWORD,
socketID: request.query.socketID,
});
return token;
});
fastify.post("/send-event", async (request, reply) => {
try {
// Parse the request body
const { event, message } = request.body;
// Some sort of auth (implement your authentication logic here)
// Create a server stream
const stream = createServerStream({
channel: "main",
id: process.env.SERVER_ID,
region: process.env.SERVER_REGION,
password: process.env.SERVER_PASSWORD,
});
// Send the event and message
await stream.send(event, message);
// Return a success response
return reply.send({ success: true, message: "Event sent successfully" });
} catch (error) {
return reply.status(500).send({ success: false, message: error });
}
});
// Start the server
const start = async () => {
try {
await fastify.listen({ port: PORT });
console.log(`Server listening on port ${PORT}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();