Document is undefined - server side


I was wondering how I would go about using something like document.write in the server.js. It keeps telling me that its undefined and I don’t know how to go about fixing this?


It makes completely sense that document is undefined in the Node process, as document is a client variable for the actual HTML document, you should use websockets if you want to write something to the DOM from the server’s side.

E.g. usage of is very easy:


const Express = require("express");
const App = Express();
const Server = require("http").createServer(App);
const io = require("")(Server);

App.use(Express.static(__dirname + "/public"));

io.on("connection", async socket => {
  socket.emit("writeToDocument", "<h1>This was added serverside</h1>");

Server.listen(3000, () => console.log("Server is listening on port 3000"));


    <meta charset="utf-8" />
    <title>Test thingy</title>
    <h1>Hello World</h1>
    <script src="/"></script>
      const socket = io.connect(location.origin);
      socket.on("writeToDocument", data => document.body.innerHTML += data);


Thanks for your help.