how to integrate ssl in websocket through nextjs?

Viewed 4676

I am given to understand that if I want to use wss I need to have certification and key so I generated two

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 100 -nodes

I have a code which works in Express but does not work as following :

const server = https.createServer({
  cert: fs.readFileSync('/www/wwwroot/mydomain/cert/cert.pem'),
  key: fs.readFileSync('/www/wwwroot/mydomain/cert/key.pem')
});

console.log(server)
const wss = new Websocket.Server({ server })
server.listen(8082)

How can I run wss in nextjs?

1 Answers

Seems like you might be after a two part answer:

  • How to set up a socket api in NextJS
  • How to authenticate that api with pem files

How to set up a socket api in NextJS

As usual I would direct you to the examples on the project. They are really good and have solved a lot of my questions in the past.

In this case I didn't find any examples for web-sockets, but after a bit of digging I found this sample.

https://github.com/vercel/next.js/tree/442fbfaa4d4e8205cf10c7e5d27b8f51b7a4bdc6/examples/with-socket.io

How to authenticate that api with pem files

Using the sample above and your auth logic, you should be able to do everything around the WSS server before you tell the NextJs what do do.

Your wssServer logic will define what is possible and your NextJsServer is acting like a middleman, defining which queries go where.

https://github.com/vercel/next.js/blob/442fbfaa4d4e8205cf10c7e5d27b8f51b7a4bdc6/examples/with-socket.io/server.js

// server.js
const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const nextApp = next({ dev })
const nextHandler = nextApp.getRequestHandler()

// fake DB
const messages = {
  chat1: [],
  chat2: [],
}

// socket.io server
io.on('connection', socket => {
  socket.on('message.chat1', data => {
    messages['chat1'].push(data)
    socket.broadcast.emit('message.chat1', data)
  })
  socket.on('message.chat2', data => {
    messages['chat2'].push(data)
    socket.broadcast.emit('message.chat2', data)
  })
})

nextApp.prepare().then(() => {
  app.get('/messages/:chat', (req, res) => {
    res.json(messages[req.params.chat])
  })

  app.get('*', (req, res) => {
    return nextHandler(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})
Related