Using a hook to pass variables between client and server

  • I'm trying to pass server-side data into the client side JavaScript file. Is there a way I can do this (maybe using a hook)?

    Sorry, I am new to NodeBB.

  • Community Rep

    The best way is to use

    You use to create an event in your server code like so,

    // Require
    var socketPlugins = require.main.require('./src/')
    // Your plugin's app.load hook
    plugin.load = function (data, next) {
      // Create a socket namespace
      socketPlugins.yourplugin = {}
      // Create the event
      socketPlugins.yourplugin.eventname = function (socket, data, callback) {
        // The client will call this event to request data and optionally send its own data.
        // Use the callback to send the data it wants. First parameter is an error value.
        callback(null, {requestedinfo: 'I got the info'})

    In the client .js you call the event like so...

    // The middle parameter is optional data you can send to the server.
    socket.emit('plugins.yourplugin.eventname', {}, function (err, data) {

  • @yariplus Thanks!

Suggested Topics

| | |

© 2014 – 2022 NodeBB, Inc. — Made in Canada.