Categories
JavaScript Answers

How to add authentication with Socket.IO and JavaScript?

To add authentication with Socket.IO and JavaScript, we call send to get the key from client side and receive it on server side.

For instance, we write

const jwt = require("jsonwebtoken");
//...
app.post("/login", (req, res) => {
  const profile = {
    first_name: "John",
    last_name: "Doe",
    email: "john@doe.com",
    id: 123,
  };

  const token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60 * 5 });
  res.json({ token });
});

to add the /login endpoint.

Then we call jwt.sign to return am auth token with the profile data.

Then we write

const socketioJwt = require("socketio-jwt");
const sio = socketIo.listen(server);

sio.set(
  "authorization",
  socketioJwt.authorize({
    secret: jwtSecret,
    handshake: true,
  })
);

sio.sockets.on("connection", (socket) => {
  console.log(socket.handshake.decoded_token.email, "has joined");
});

to use the socketio-jwt package to add authentication to Socket.io.

We use it to add JWT authentication with secret set to jwtSecret.

And we listen to the connection event with handler that gets the decoded token’s email.

Categories
JavaScript Answers

How to execute the start script with Nodemon with JavaScript?

To execute the start script with Nodemon with JavaScript, we use the --exec option.

For instance, we run

nodemon --exec npm start

to run npm start with nodemon with the --exec option.

Categories
JavaScript Answers

How to make Sequelize use singular table names with JavaScript?

To make Sequelize use singular table names with JavaScript, we set freezeTableName to true.

For instance, we write

const Sequelize = require("sequelize");

const opts = {
  define: {
    freezeTableName: true,
  },
};

const sequelize = new Sequelize(
  "mysql://root:123abc@localhost:3306/mydatabase",
  opts
);

const Project = sequelize.define("Project", {
  title: Sequelize.STRING,
  description: Sequelize.TEXT,
});

to create a Sequelize instance with the define.frezeTableName property set toi true to stop table names from being pluralized when they’re created.

Then we call sequelize.definer to create the Project model which is mapped to a table that isn’t pluralized.

Categories
JavaScript Answers

How to uninstall all dependencies listed in package.json (NPM) with JavaScript?

To uninstall all dependencies listed in package.json (NPM) with JavaScript, we run npm uninstall.

For instance, we run

npm uninstall *

in the node_modules folder to uninstall all the modules installed in the folder.

Categories
JavaScript Answers

How to use to npm start run a server on port 8000 with JavaScript?

To use to npm start run a server on port 8000 with JavaScript, we use the --port option.

For instance, we run

npm start --port 8000

to run the start script on port 8000.