Document is undefined - server side


#1

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?


#2

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 socket.io is very easy:

server.js

const Express = require("express");
const App = Express();
const Server = require("http").createServer(App);
const io = require("socket.io")(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"));

public/index.html

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

#3

Thanks for your help.