How to use websockets in Next js

Viewed 5575

I am using Next js for server sider rendering of my application. However, I also need to connect to the Gamesparks library(for authentication) which uses websockets. Every time I try to add my script to the head tag, I get errors that it's not working. Is it possible to use websockets in Next js? I've seen a lot about socket io, and was considering it, but I'd have to re-write the attached library. I'm also curious, should I instead attempt to do my own backend Express server to manage these connections?

As you can probably tell, I'm new to web-development so any resources or suggestions would be appreciated!

The error message from the browser is http://localhost:3000/gamesparks/gamesparks-rt.js net::ERR_ABORTED 404 (Not Found)

1 Answers

The error is almost always helpful.

That one implies it can't find that JavaScript file, so you'll need to figure out why. Is your server set up to serve static assets? You'll need to configure this:

app.use(express.static('public'))

Where you've put that file in public/gamesparks/gamesparks-rt.js relative to your Express project.

This is what a 404-type error usually refers to: Your browser requested the file and was told it didn't exist. As Express won't serve up "static" files unless you tell it to, you'll need to configure it.

Related