
Conosciamo tutti la messaggistica istantanea e la usiamo per chattare con le persone in tempo reale. A volte, tuttavia, potremmo desiderare un'app che ci consenta di inviare messaggi in modo anonimo agli amici o di chattare in modo anonimo con estranei nelle immediate vicinanze. Un esempio di tale app è Truth, che ti consente di parlare con le persone nel tuo elenco di contatti senza rivelare la tua identità.
In questo tutorial, ti mostrerò come creare un'app di chat anonima pubblica in JavaScript (utilizzando NodeJS ed Express sul server e VanillaJS sul client) e Pusher. Pusher ci consente di creare applicazioni in tempo reale scalabili e affidabili. Poiché abbiamo bisogno della consegna in tempo reale dei messaggi di chat, questo è un componente chiave dell'app di chat. L'immagine sotto mostra ciò che costruiremo:

Iniziare
Cominciamo registrandoti per un account Pusher gratuito (o effettuando l'accesso se ne hai già uno). Dopo aver effettuato l'accesso, crea una nuova app Pusher dalla dashboard e prendi nota dell'ID app, della chiave e del segreto, che sono univoci per un'app.
Per creare una nuova app Pusher, fai clic sul Your apps
menu laterale, quindi fai clic suCreate a new app
pulsante sotto il cassetto. Questo fa apparire la procedura guidata di configurazione.
- Immettere un nome per l'applicazione. In questo caso, la chiamerò "chat".
- Seleziona un cluster.
- Seleziona l'opzione "Crea app per più ambienti" se desideri avere istanze diverse per sviluppo, gestione temporanea e produzione.
- Seleziona Vanilla JS come frontend e NodeJS come backend.
- Completa il processo facendo clic sul
Create my app
pulsante per configurare l'istanza dell'app.

Code-up del server
We need a backend which will serve our static files and also accept messages from a client and then broadcast to other connected clients through Pusher. Our backend will be written in NodeJS, so we need to set it up.
We need a package.json
file, and I’ll add it by running the command below. I’ll use the defaults provided by hitting enter for every prompt.
With the package.json
file added, I’ll install Express, body-parser, and Pusher npm packages. Run the following command:
With these packages installed, let’s add a new file called server.js
with the following content:
var express = require('express');var bodyParser = require('body-parser');var Pusher = require('pusher');
var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));
var pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER" });
app.post('/message', function(req, res) { var message = req.body.message; pusher.trigger( 'public-chat', 'message-added', { message }); res.sendStatus(200);});
app.get('/',function(req,res){ res.sendFile('/public/index.html', {root: __dirname });});
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 5000;app.listen(port, function () { console.log(`app listening on port ${port}!`)});
With the code above, we have defined an end-point /message
which will be used by one client to send a message to another through Pusher. The other routes are used to serve the static files which we will add later.
Replace the placeholder strings App ID, Secret, and Key with the values from your Pusher dashboard. Add this statement "start": "node server.js"
in the script property of our package.json
file. This will allow us to start the server when we run npm start.
Building the frontend
Moving on to the frontend, let’s add a new folder called public. This folder will contain our page and JavaScript files. Add a new file called style.css with the content below, which will hold our style definition for the page.
@import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");.chat{ list-style: none; margin: 0; padding: 0;}
.chat li{ margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px dotted #B3A9A9;}
.chat li.left .chat-body{ margin-left: 60px;}
.chat li.right .chat-body{ margin-right: 60px;}
.chat li .chat-body p{ margin: 0; color: #777777;}
.panel .slidedown .glyphicon, .chat .glyphicon{ margin-right: 5px;}
.body-panel{ overflow-y: scroll; height: 250px;}
::-webkit-scrollbar-track{ -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); background-color: #F5F5F5;}
::-webkit-scrollbar{ width: 12px; background-color: #F5F5F5;}
::-webkit-scrollbar-thumb{ -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); background-color: #555;}
Add another file called index.html with the markup below.

Original text
Anonymous Chat - Refresh
- Available
- Busy
- Away
- Sign Out
Send

{{body}}
{{body}}
I’m using a template from bootsnipp which has been slightly modified to display just the name and message.
Add a new file called index.js with the content below. Remember to add the Pusher app details:
$(document).ready(function(){ var pusher = new Pusher('APP_KEY', { cluster: 'APP_CLUSTER', encrypted: false });
let channel = pusher.subscribe('public-chat'); channel.bind('message-added', onMessageAdded);
$('#btn-chat').click(function(){ const message = $("#message").val(); $("#message").val("");
//send message $.post( "//localhost:5000/message", { message } ); });
function onMessageAdded(data) { let template = $("#new-message").html(); template = template.replace("{{body}}", data.message);
$(".chat").append(template); }});
With the code in this file, we get the message to be sent and then call the server with the message. After that, we connect to Pusher by creating a new Pusher object with the App Key and the Cluster that you set earlier.
We subscribe to a channel and an event named message-added
. The channel is a public channel so it can be named any way you like. I’ve chosen to prefix mine with public-
but that’s just my own personal naming convention as there are no rules for a public channel. The difference between a public
channel and a private
or presence
channel is that a public channel does not require a client to be authenticated and can be subscribed to by anyone that knows the name of the channel. You can read more about Pusher channels here.
We bind to the click event of the chat button on the page, retrieve the message from the textbox on the page, and then send it to the server with the username. With all we have setup, we can start the app by running npm start
. Here’s a glimpse of how it works on my computer.

Wrap Up
This is a app to show how you can use Pusher to send messages in real-time. We built a public anonymous chat app that allows your website visitors to send anonymous messages to each other in real-time. You can find the code here on GitHub
This was originally published on Pusher