5.9. Creating a basic server with NodeJS: Request validation and authentication
Page 40 | Listen in audio
NodeJS is a powerful platform for creating web applications. In this section, we'll explore how to create a basic server with NodeJS, focusing specifically on validating and authenticating requests. This is critical to ensuring the security and integrity of the data in your application.
Creating a basic server
To start, let's create a basic HTTP server with NodeJS. First, you need to install NodeJS and npm (Node Package Manager) on your computer. Once installed, you can create a new JavaScript file, say server.js
, and add the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server listening on port 3000');
});
This code creates an HTTP server that listens on port 3000 and responds with "Hello World" to all requests. To start the server, you can run the command node server.js
in the terminal.
Request Validation
Request validation is a crucial part of any web application. It ensures that data received from the customer is in the correct format and complies with all business rules. To add request validation to our server, we can use a library called joi
. First install it with the command npm install joi
and then import it into your server.js file:
const Joi = require('joi');
Now, you can define a validation scheme for your requests. For example, if you are creating an API for a blog, you might want to validate blog post requests like this:
const schema = Joi.object({
title: Joi.string().min(3).max(30).required(),
content: Joi.string().min(5).required(),
});
This scheme defines that the blog post title must be a string with a minimum of 3 and a maximum of 30 characters, and the post content must be a string with a minimum of 5 characters. You can use this scheme to validate requests like this:
const validation = schema.validate(req.body);
if (validation.error) {
res.status(400).send(validation.error.details[0].message);
return;
}
Authentication of requests
Authentication is another crucial part of any web application. It ensures that only authorized users can access certain features. To add authentication to our server, we can use a library called passport
. First install it with the command npm install passport
and then import it into your server.js file:
const passport = require('passport');
Passport supports many authentication strategies, such as local authentication, OAuth, and JWT. For this example, we are going to use local authentication. First, we need to configure the Passport:
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
This code configures Passport to use the local strategy. It tries to find a user with the given username and checks the password. If the password is correct, the user is authenticated.
To secure a route with authentication, you can use Passport's authenticate
method:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
This code secures the /login route with local authentication. If authentication succeeds, the user is redirected to the / route. If it fails, the user is redirected to the /login route.
In summary, creating a basic server with NodeJS involves configuring the server, validating requests, and authenticating users. Validation ensures that incoming data is in the correct format, while authentication ensures that only authorized users can access certain resources.
Now answer the exercise about the content:
What is the purpose of validating requests in a web application created with NodeJS?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: