Unhandled Promise Rejection Warning: ReferenceError: window is not defined

const path = require("path");

const express = require("express");

const router = new express.Router();

const Moralis = require("moralis/node");

router.get("/", async (req, res) => {
    res.render("home", {
        title: "Home",
        shared_data,
    });
});

router.get("/dashboard", async (req, res) => {
    res.render("dashboard", {
        title: "Dashboard",
    });
});

router.get("/login", async (req, res) => {

    Moralis.initialize(
        "APP ID",
        "",
        "MASTER KEY"
    );

    Moralis.serverURL = "SERVER URL"; 
    user = await Moralis.Web3.authenticate();
    if (user) {
        console.log(user);
        console.log(user.attributes.ethAddress);
        user.save();
    }
    res.redirect("/");
});

module.exports = router;

The above code is showing the following error:
UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
on user = await Moralis.Web3.authenticate(); this line.
I have followed the Moralis documentation for NodeJS.

Hey @Psy

SSR is launched in a Node.js environment where there is no access to the browser objects. To create a universal application, you need to check their presence:

if (window) {
  // code will run on the brower
} else {
 // code will run on the server only
}

Thanks for the reply @Yomoo. Can you please tell me some solution so that I can authenticate the user on the server-side smoothly? Maybe a workaround or an npm package that I may be missing?

@Psy
Authorization is provided only through the website.

Moralis is used to create a serverless application which means no server-side code needed.

the Moralis.Web3 object you are using is available on browser side hence accessible only through browser object.

The browser programming environment and window is completely separate from node.js so you cannot call that directly from node.js. Server-side code runs on the server in node.js. Client-side code in the browser runs in the browser only. The two may communicate via Ajax requests or messages sent over a webSocket connection, but they can’t call code in each other directly.

source: https://stackoverflow.com/questions/33313854/how-can-i-access-the-browsers-window-object-from-a-nodejs-application/33314014

2 Likes

Thanks a lot @Moralis_DAO and @Yomoo

1 Like