NodeJS/Express API real time notification with React frontend - node.js

I am trying to implement real time notifications. The current code looks something like:
exports.doFooBar = asyncHandler(async (req, res, next) => {
// doing something here
// ...................
const onlyAfewUsers = getUsersWhoShouldBeNotified();
// somehow notify the users that are in "onlyAfewUsers"
// ... something else
res.status(200).json({
status: "success",
message: "......"
});
});
The frontend is a react webapp that consumes this API. I've looked into socket.io and that seems like something that I can use in my case. But, how do I figure out how to "look"/"poll" for notifications on the React frontend?

Please explain a little more about the usecase.
Also tell you need to send the push notifications(Firebase messaging) or basic in app notification in navbar like stackoverflow.

Related

Is it bad practice to wrap express app within socketio connection?

I'm making a webgame, and if I have a route that looks like:
app.post('/create_account', (req, res) => {
var email = req.body.email
var pass = req.body.pass
res.json({response: "created"})
})
Anyone can post data to mywebsite.com/create_account using postman, or curl or something, and my website will start creating account for them even though they are not even on my webpage.
I found an interesting workaround, and I wanted to know if this is safe, or even a good idea. Basically I wrap my app routes within a socket.io connection:
io.on('connection', function(socket) {
app.post('/create_account', (req, res) => {
//code goes here
})
})
I tested it, and it seems that this way you can only post to /create_account if you are actually connected to the webpage.
What (if any) are the disadvantages to doing this? If this is a bad idea, whats's a better way to prevent people from posting data if they aren't on my site.
#Ruslan's suggestion about CSRF tokens is sound and probably your best option, wrapping everything in socket.io seems like too much complexity. Here's a library that does that: https://github.com/expressjs/csurf

Making and changing APIs when online in Nodejs

So were trying to develop an application (or Service) with Node.js that provides each user a custom API that can be called from {theirUserName}.ourwebsite.com. Users will be able to change/edit/remote the endpoints of the API within the application through our editor. They can add params to the endpoints, add auth, etc.
Now my question is, how can we make the API online at first, then how can we change the endpoints online without stopping the API application and running again?
P.S: APIs configuration will be saved into a JSON that will be saved to the DB and once the configuration change an event will be raised that tells us the endpoints have changed.
Using Express, you can add routes after the server is listening, so it's not a problem. Beware of precedence as it will be added at the bottom of the stack.
I would advise to have a db storing routes, and when running the node app (before listening) load all the routes in db and add them to the router. In order to be able to scale your app as well as being able to restart it safely.
Then start listening, and have a route for adding routes, deleting routes, updating routes etc.
Here is a simple example of adding a route after listening :
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const someGenericHandler = function(req, res) {
return res.json({ message: 'foobar' });
};
// it creates a route
app.post('/routes', function(req, res) {
try {
const route = req.body;
app[route.method](route.path, someGenericHandler);
return res.json({ message: `route '${route.method}${route.path}' added` });
} catch(err) {
return res.status(500).json({ message: err.message || 'an error occured while adding the route' });
}
});
app.listen(process.env.PORT);
You can try this code, paste it in a file, let say index.js.
Run npm i express body-parser, then PORT=8080 node index.js, then send a POST request to http:/localhost:8080/routes with a json payload (and the proper content-type header, use postman)
like this: { method: 'get', path:'/' } and then try your brand new route with a GET request # http://localhost:8080/'
Note that if you expect to have hundreds of users and thousands of requests per minute, I would strongly advise to have a single app per user and a main app for user registering and maybe spawn a small VPS per app with some automation scripts when a user register, or have some sort of request limit per user.
Hope this helps

Node Express API + Front-End

I'm coding my first "solo" nodejs webapp. Its based on a previous app (that I coded by following some kind of tutorial/course) which was an Express REST API that allows you to add/remove/update/list a Todo list. I've also implemented user authentication using jwt/bcrypt. All this is stored in a MongoDB database.
Also note that all the endpoints return JSON.
I'm now trying to add a front-end to the app. The API endpoints are at /api/endpoint1, /api/endpoint2, etc., and the views are rendered on /view1, /view2, etc. I'm doing this on purpose so that I can get the responses in plain JSON from the API, or show it in a webpage rendered.
I started by using jQuery's ajax to make the calls but I realized this was not the way I wanted to do this. I removed all the js scripts on my webpage and started working directly on the server, rendering the pages with the info fetched from the api.
This is what I have now:
server.js (main file) [sample]
// RENDER 'GET TODOs'
app.get('/todos', authenticate, (req, res) => {
let auth = req.cookies['x-auth'];
request({
url: 'http://localhost:3000/api/todos',
headers: {
'x-auth': auth
}
}, function (error, response, body) {
if (error || response.statusCode !== 200) {
return res.status(response.statusCode || 500).send('Error'); // TODO
}
let bodyJSON = JSON.parse(body);
res.render('todos', {
title: 'Todo App - Todos',
todos: bodyJSON.todos
});
});
});
// API endpoint to 'GET TODOs' (JSON)
app.get('/api/todos', authenticate, (req, res) => {
Todo.find({
_creator: req.user._id
}).then((todos) => {
res.send({todos});
}, (err) => {
res.status(400).send(err);
});
});
I don't know why, but all this looks weird to me. I'm wondering if this is how I'm supposed to do this. I mean, is this a good approach/practice on making a API+front-end node app ?
Also, I'm using an auth middleware twice: in the views and in the API itself. I guess this is OK?
It would probably be better to use React/Angular but this is such a small app and I just wanted to make a really simple front-end.
Just keep things simple.
If you go with server-side HTML rendering, you don't need a REST API, just drop it. You need an API in case of an ajax frontend or mobile app.
If you needed a combined approach (server-side rendering + mobile app or server side rendering with some ajax), at the very first step you would want to isolate your database querying code into a separate module (which is actually always a good idea) and use the module from your API and from your views directly, avoiding API usage from server-side views.
This way you will eliminate excessive auth and make debugging much easier, also your code will become cleaner, thus more maintainable.
Also, React is not that complex, i would definitely give it a shot :)

What is the best way to connect react.js UI to my node.js API and mongoDB?

I'm working on my first project and would like to know if socket.io is the only or the best solution to connect my UI to node.
Is there anything else you could recommend me? Real-time is not important, I just want to access my data. Simple keywords would already help me a lot.
Thank you!
GT
It is pretty straightforward:
Make sure your node.js server returns (JSON) data on certain calls, e.g.
//this is your API endpoint
app.use('/api/endpoint', (req, res, next) => {
res.send({
key: 'value'
});
});
//this sends your html file with react bundle included
//has to be placed after the api handling
app.use('*', (req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
You don't have to serve your html with the same server, but it normally makes sense.
Now, you can make API calls inside your React app to fetch the data. I like to use axios (https://github.com/mzabriskie/axios), but you can make the calls however you want.
You should make the call and save it somehow, either in state or in your store if you use redux.
E.g.:
...
componentDidMount() {
axios.get('http://yourserver.com/api/endpoint')
.then(function (response) {
this.setState({
data: response.data
});
})
.catch(function (error) {
console.log(error);
});
}
...
Sending Data to your node server to store it in a DB is pretty similar.
Please note, that this is just a basic example, you will encounter some issues along the way, especially when you go to production, such as CSRF protection or JWT for securing your API. However, this should get you started!

Socket.io and request and response objects

I'm quite new on node.js and now I'm learning socket.io.
I'm developing an app step by step so, at this time, I have an app that can login an user, do crud operation in mysql and mongodb and upload files, all these operations are manage with some web pages with HTML and javascript technologies launched directly from restify.
After that I'm tring to add socket functionality to, at this time, simple print who is online.
So, before I have something like:
server.get('/login', function(req, res, next){ ... });
and now I have something like:
socket.on("login", function (req, res, next){ ... });
but, naturally, req and res are undefined!
Are there the same objects into socket.io?
To my understanding, you want to pass values back and forth in your request and response using socket.io.
Yes it is possible to do that and you syntax should be something like this...
Using express.js:
io.on('login', function(req){
client.emit('response event', { some: 'data' });
Note: when using emit you send the data to everyone, you have other methods like .broadcast(), .to(), etc.. for other use cases refer to socket.io github for better understanding
And lastly, inside emit you define the function you want to call on the client side and the data you want to send to the client.

Resources