Import modules inside the server.config.js

Hello everyone!
I have the following server.config.js:

/**
 * This file allows you to configure the Fastify Server settings
 * used by the RedwoodJS dev server.
 *
 * It also applies when running RedwoodJS with `yarn rw serve`.
 *
 * For the Fastify server options that you can set, see:
 * https://www.fastify.io/docs/latest/Reference/Server/#factory
 *
 * Examples include: logger settings, timeouts, maximum payload limits, and more.
 *
 * Note: This configuration does not apply in a serverless deploy.
 */

/** @type {import('fastify').FastifyServerOptions} */
const config = {
  requestTimeout: 15_000,
  logger: {
    // Note: If running locally using `yarn rw serve` you may want to adust
    // the default non-development level to `info`
    level: process.env.NODE_ENV === 'development' ? 'debug' : 'warn',
  },
  watchOptions: {
    ignored: ['api/folders/**/*'],
  },
}

/**
 * You can also register Fastify plugins and additional routes for the API and Web sides
 * in the configureFastify function.
 *
 * This function has access to the Fastify instance and options, such as the side
 * (web, api, or proxy) that is being configured and other settings like the apiRootPath
 * of the functions endpoint.
 *
 * Note: This configuration does not apply in a serverless deploy.
 */

/** @type {import('@redwoodjs/api-server/dist/fastify').FastifySideConfigFn} */
const configureFastify = async (fastify, options) => {
  if (options.side === 'api') {
    fastify.log.info({ custom: { options } }, 'Configuring api side')

    fastify.register(require('@fastify/websocket'))

    // Create an instance of the AlascomSocketServer
    const socketServer = new SocketServer(fastify)
    // Connect to the TCP server
    socketServer.connect()

    fastify.register(async (fastify) => {
      fastify.get('/ws', { websocket: true }, (connection) => {
        fastify.log.info('Server connected')

        // Set the WebSocket connection in the SocketServer instance
        socketServer.setConnection(connection)

        connection.socket.on('message', (message) => {
          fastify.log.info(`/ws message: ${message}`)

          // Use the SocketServer instance to send messages to the client
          socketServer.send(message)
        })
        connection.socket.on('error', (error) => {
          console.log('Connection error', error)
        })

        connection.socket.on('close', () => {
          console.log('Client disconnected')
        })
      })
    })
  }

  if (options.side === 'web') {
    fastify.log.info({ custom: { options } }, 'Configuring web side')
  }

  return fastify
}

Now of course, the SocketServer class needs to be imported. However, whenever I try to import it like const socketServer = require("src/socket") it says that it cannot find the module. It also does not work with absolute path nor with /api/src/socket. What is the correct way to do this?

1 Like

Hi. How do you plan to deploy? Is this an app that would be running on local hardware (seem to recall a Discord discussion to that effect re: WebSockets).

If you you might want to try the experimental server file – which runs the entire api w/in a Fastify server.

It has more confidence options and might suit your use case better – and can give feedback on this upcoming feature: Fastify Server File [Experiment] - #2

It’s still early and changes will happen, but will be used for serverful GraphQL subscription and live queries with RedwoodJS realtime.

Yes, it is an application deployed on a physical machine, and it has to be scoped within the local network of the computer it is deployed on (long story short: two workstations, only one of which hosts the code and the other connects through ip address, and that’s it). The thing is that the WebSocket I was mentioning also needs access to the Prisma instance, so all of this needs to be done outside of the config file. I will try the file you mentioned, thank you very much!

My use case is actually way simpler; isn’t there a way to modify the server.config.js file to be a module? This way, I could import what I need from the backend