ExpressJS Interview Questions and Answers
1. What is the default port number for an [Link] application?<br/>[Link] does not have a fixed default
port.<br/>Developers usually run apps on port 3000 by convention.<br/>You can specify any port when starting the
server.<br/>Example:
const express = require('express');<br/>const app = express();
[Link]('/', (req, res) => [Link]('Hello Express'));
[Link](3000, () => {<br/> [Link]('Server running on port 3000');<br/>});<br/>2. What is middleware in
[Link]?<br/>Middleware functions are functions that have access to req, res, and next objects. They execute
code, modify requests/responses, or end the request-response cycle.
3. What is the role of next() in middleware?<br/>The next() function is a callback that middleware uses to pass control
to the next middleware function in the stack.
If next() is not called, the request will hang (never move forward).<br/>If next() is called, the request moves to the next
middleware or route handler.<br/>4. What is routing in [Link]?<br/>Routing refers to how an application’s
endpoints (URIs) respond to client requests.
Example:
[Link]('/home', (req, res) => {<br/> [Link]('Welcome to Home Page');<br/>});<br/>5. Difference between [Link]()
and [Link]()?<br/>[Link]() → used to mount middleware functions.<br/>[Link]() → handles GET requests for a
specific route.<br/>6. Differentiate between NodeJS and ExpressJS?<br/>NodeJS
ExpressJS
A runtime environment that allows JavaScript to be executed outside the browser.
A web framework built on top of NodeJS to simplify server-side development.
A server-side JavaScript runtime.
A backend web framework based on NodeJS.
Can be used to create APIs but requires extra effort.
Provides an easy and structured way to develop RESTful APIs.
Slightly faster as it's minimal and doesn't include extra abstractions.
Adds a slight overhead due to additional features but is still highly efficient.
Ideal for low-level operations, real-time applications, microservices, and command-line tools.
Ideal for web applications, APIs, RESTful services, and middleware-based projects.
7. Mentions few features of ExpressJS.<br/>Few features of the ExpressJS includes
Routing: Express provides a simple way to define routes for handling HTTP requests. Routes are used to map
different URLs to specific pieces of code, making it easy to organize your application's logic.<br/>Middleware:
Express uses middleware functions to perform tasks during the request-response cycle. Middleware functions have
access to the request, response, and the next middleware function.<br/>HTTP Utility Methods: Express mainly used
for handling HTTP methods like GET, POST, PUT, and DELETE. This makes it easy to define how the application
should respond to different types of HTTP requests.<br/>Static File Serving: It can also serve static files, such as
images, CSS, and JavaScript, with the help of built-in [Link] middleware.<br/>Security: It includes features
and middleware to strengthen the security of your web applications, such as the helmet middleware to secure your
app.<br/>8. What are some popular alternatives to ExpressJS?<br/>There are several popular alternatives to
ExpressJS which includes:
[Link]<br/>[Link]<br/>[Link]<br/>Fastify<br/>9. Which major tools can be integrated with ExpressJS?<br/>There
are many tools and libraries that can be integrated with ExpressJS such as:
Database tools: MongoDB, MySQL, PostgreSQL.<br/>Template Engines: EJS, Pug, Mustache.<br/>Authentication
libraries: [Link].<br/>Logging libraries: Morgan, Winston.<br/>Validation libraries: Joi,
express-validator.<br/>ORM libraries: Sequelize, Mongoose.<br/>10. What is .env file used for?<br/>The .env file is
used for storing sensitive information in a web application which we don't want to expose to others like password,
database connection string etc. It is a simple text file where each line represents a key-value pair, and these pairs are
used to configure various aspects of the application.
11. What are JWT?<br/>JSON Web Tokens are mainly a token which is used for authentication and information
exchange. When a user signs in to an application, the application then assigns JWT to that user. Subsequent
requests by the user will include the assigned JWT. This token tells the server what routes, services, and resources
the user is allowed to access. Json Web Token includes 3 part namely- Header, Payload and Signature.
12. Create a simple middleware for validating user.
// Simple user validation middleware<br/>const validateUser = (req, res, next) => {<br/> const user = [Link];
if (!user) {<br/> return [Link](401).json({ error: 'Unauthorized - User not found' });<br/> }
next();<br/>};
[Link]('/profile', validateUser, (req, res) => {<br/> const user = [Link];<br/> [Link]({ message: 'Profile page',
username: [Link] });<br/>});<br/>13. What is Bcrypt used for?<br/>Bcrypt is a password hashing function
which is used to securely hash and store user passwords. It is designed to be slow and computationally intensive,
making it resistant to brute-force attacks and rainbow table attacks. Bcrypt is a key component in enhancing the
security of user authentication systems.
14. Why should you separate the Express app and server?<br/>In ExpressJS, it is recommended to separate the
Express App and the server setup. This provides the modularity and flexibility and makes the codebase more easier to
maintain and test. Here are some reasons why you should separate the Express app and server:
Modularity: You can define routes, middleware, and other components in the Express app independently of the server
configuration.<br/>Ease of Testing: Separation makes it easier to write unit tests for the Express app without starting
an actual server. You can test routes, middleware, and other components in isolation.<br/>Reusability: You can reuse
the same Express app in different server configurations.<br/>Configuration Management: Separating the app and
server allows for cleaner configuration management.<br/>Scalability: It provides a foundation for a scalable code
structure. As your application grows, it will easier to maintain the code.<br/>15. What do you understand about
ESLint?<br/>EsLint is a JavaScript linting tool which is used for automatically detecting incorrect patterns found in
ECMAScript/JavaScript code. It is used with the purpose of improving code quality, making code more consistent, and
avoiding bugs. ESLint is written using NodeJS to provide a fast runtime environment and easy installation via npm.
16. Define the concept of the test pyramid.<br/>The Test Pyramid is a concept in software testing that represents the
distribution of different types of tests. It was introduced by Mike Cohn, and it suggests that a testing strategy should be
shaped like a pyramid, with the majority of tests at the base and fewer tests as you move up. The Test Pyramid
consists of three levels: Unit Tests, Integration Tests, and End-to-End (E2E) Tests.
17. Differentiate between [Link]() and [Link]().<br/>Feature
[Link]()
[Link]()
Purpose
Sends a response of any type (string, object, array, buffer, etc.).
Specifically sends a JSON response.
Data Handling
Converts objects/arrays into JSON automatically, but also supports sending other data formats.
Converts objects/arrays into JSON format explicitly.
Response Type
Can send text, HTML, JSON, or any other data type.
Only sends JSON-formatted responses.
Use Case
Used when sending various types of responses, including HTML pages, strings, or JSON data.
Used specifically for sending JSON responses in APIs.
Example Usage
[Link]('Hello World!')
[Link]({ message: 'Success' })
18. What is meant by Scaffolding in ExpressJS?<br/>Scaffolding in ExpressJS refers to the process of generating a
basic project structure automatically. This can speed up the initial setup and help maintain consistency in the way
projects are structured, especially in large teams.
19. How would you install an Express application generator for scaffolding?<br/>Express application generator are
used for quickly setting up a new Express application with some basic structure. You can install it using Node
Package Manager (npm), which comes with NodeJS.
To install it globally:
npm install -g express-generator<br/>20. What is Yeoman and how to install Yeoman for scaffolding?<br/>Yeoman is
a scaffolding tool for web applications that helps developers to create new projects by providing a generator-based
workflow.
To install Yeoman run the following command:
npm install -g yo<br/>Yeoman works with generators, which are packages that define the structure and configuration
of a project. You can install a generator like this:
npm install -g generator-express<br/>Once installed, you can use Yeoman to create a new application:
yo appname<br/>21. What is CORS in ExpressJS?<br/>CORS (Cross-Origin Resource Sharing) is a security feature
implemented by web browsers to control how web pages in one domain can request and interact with resources
hosted on another domain.
In the context of ExpressJS, CORS refers to a middleware that enables Cross-Origin Resource Sharing for your
application. This allows the application to control which domains can access your resources by setting HTTP headers.
22. What are Built-in Middlewares?<br/>ExpressJS, includes a set of built-in middlewares that provide common
functionality. These built-in middlewares are included by default when you create an Express application and can be
used to handle various tasks. Here are some of the built-in middlewares in Express:
ExpressJSon(): This middleware is used to parse incoming JSON requests. It automatically parses the request body if
the Content-Type header is set to application/json.<br/>[Link](): The [Link]() function is often used
to create modular route handlers. It allows you to group route handlers together and then use them as a
middleware.<br/>[Link](): This middleware is used to serve static files, such as images, CSS, and JavaScript
files, from a specified directory.<br/>23. How would you configure properties in ExpressJS?<br/>In ExpressJS, you
can configure properties using the [Link]() method. This method allows you to set various properties and options
which affects the behavior of the Express application.
[Link](name, value);<br/>Here, name represents the name of the property you want to configure, and value is the
value you want to assign to that property. Express provides a wide range of properties that you can configure based
on your application's requirements.
24. Which template engines do Express support?<br/>ExpressJS supports any template engine that follows the (path,
locals, callback) signature.
25. Elaborate on the various methods of debugging on both Linux and Windows systems?<br/>The debugging is the
vital need at the time of software development to identifying issues in the application's logic, handling of HTTP
requests, middleware execution, and other aspects specific to web development. Here are some methods commonly
used for debugging an ExpressJS application on both Linux and Windows:
[Link]: The simplest way to debug an ExpressJS application is by using [Link](). You can output
messages to the console which can be viewed in the terminal.<br/>Node Inspector: This is a powerful tool that allows
you to debug your applications using Chrome Developer Tools. It supports features like setting breakpoints, stepping
over functions, and inspecting variables.<br/>Visual Studio Code Debugger: VS Code provides a built-in debugger
that works on both Linux and Windows. It supports advanced features like conditional breakpoints, function
breakpoints, and logpoints.<br/>Utilizing debug module: The debug module is a small NodeJS debugging utility that
allows you to create debugging scopes.<br/>26. Name some databases that integrate with
ExpressJS?<br/>ExpressJS can support a variety of the databases which includes:
MySQL<br/>MongoDB<br/>PostgreSQL<br/>SQLite<br/>Oracle<br/>27. How would you render plain HTML using
ExpressJS?<br/>In ExpressJS, you can render plain HTML using the [Link]() method or [Link]() method.
Sample code:
//using [Link]
const express = require('express');<br/>const app = express();<br/>const port = 8000;
[Link]('/', (req, res) => {<br/> const htmlContent = '<html><body><h1>Hello, World!</h1></body></html>';<br/>
[Link](htmlContent);<br/>});
[Link](port, () => {<br/> [Link](`Server is listening on port ${port}`);<br/>});<br/>28. What is the use of
'[Link]()' function?<br/>The [Link]() function in ExpressJS is used to set cookies in the HTTP
response. Cookies are small pieces of data sent from a server and stored on the client's browser. They are commonly
used to store information about the user or to maintain session data.
[Link](name, value, [options]);<br/>29. Under what circumstances does a Cross-Origin resource fail in
ExpressJS?<br/>When a Cross-Origin Resource Sharing request is made, the browser enforces certain security
checks, and the request may fail under various circumstances:
No CORS Headers: The server doesn't include the necessary CORS headers in its response.<br/>Mismatched
Origin: The requesting origin does not match the origin specified in the Access-Control-Allow-Origin
header.<br/>Restricted HTTP Methods: The browser enforces restrictions on which HTTP methods are allowed in
cross-origin requests.<br/>No Credentials: The browser makes restrictions on requests that include credentials (such
as cookies or HTTP authentication).<br/>30. What is Pug template engine in ExpressJS?<br/>Pug is a popular
template engine for ExpressJS and other NodeJS frameworks. You can use Pug to render dynamic HTML pages on
the server side. It allows you to write templates using a syntax that relies on indentation and concise tags.
31. What is meant by the sanitizing input process in ExpressJS?<br/>Sanitizing input in ExpressJS application is an
important security practice to prevent various types of attacks, such as Cross-Site Scripting (XSS) and SQL injection.
It involves cleaning and validating user input before using it in your application so that it does not contain malicious
code or can be a security risk.
32. How to generating a skeleton ExpressJS app using terminal command?<br/>To generate a skeleton for an
ExpressJS application using the terminal, you can use the Express application generator which is a command-line
tool provided by the ExpressJS framework. This generator will setup a basic directory structure which includes
necessary files, and installs essential dependencies.
Steps to generate:
Step 1: Open your terminal and install the Express application generator globally using the following command:
npm install -g express-generator<br/>Step 2: After that you can use the express command to generate your
ExpressJS app.
express my-express-app<br/>Step 3: Now go to the app directory and install the dependencies and start the app by
running-
npm install<br/>npm start<br/>33. How do you secure [Link] applications?<br/>Use [Link]<br/>Sanitize
inputs<br/>Enable HTTPS<br/>Rate limiting<br/>34. What are the types of middlewares?<br/>There are mainly five
types of Middleware in ExpressJS:
Application-level middleware<br/>Router-level middleware<br/>Error-handling middleware<br/>Built-in
middleware<br/>Third-party middleware<br/>35. List the built-in middleware functions provided by
Express.<br/>ExpressJS comes with several built-in middleware functions. Few of them are:
ExpressJSON: This is used for parsing incoming requests with JSON payloads.<br/>[Link]: This is used to
serve static files like images, CSS files, and JavaScript files.<br/>[Link]: This is used for parsing
incoming requests with URL-encoded payloads.<br/>[Link]: This is used for parse incoming requests with a raw
body.<br/>[Link]: This is used for parse incoming requests with a text body.<br/>36. Mention some third-party
middleware provided by ExpressJS.<br/>ExpressJS allows you to use third-party middleware to extend and enhance
the functionality of your web application.
Here are some commonly used third-party middleware in ExpressJS
body-parser: This middleware is used to parse incoming request bodies, allowing you to access form data or JSON
payloads on [Link].<br/>cors: This module provides middleware to enable Cross-Origin Resource Sharing (CORS)
in your Express application.<br/>morgan: Morgan is a middleware module that provides request logging
functionality.<br/>helmet: Helmet helps to secure Express apps by setting various HTTP
headers.<br/>express-session: This middleware is used for managing user sessions in your Express
application.<br/>passport: This middleware is used for implementing authentication and authorization in Express
applications.<br/>37. When application-level Middleware is used?<br/>Application-level middlewares are bound to an
instance of the Express application and are executed for every incoming request. These middlewares are defined
using the [Link]() method, and they can perform tasks such as logging, authentication, setting global variables, and
more.
38. Explain Router-level Middleware.<br/>Router-level middlewares are specific to a particular router instance. This
type of middleware is bound to an instance of [Link](). Router-level middleware works similarly to
application-level middleware, but it's only invoked for the routes that are handled by that router instance. This allows
you to apply middleware to specific subsets of your routes, keeping your application organized and manageable.
39. How to secure ExpressJS application?<br/>It is very important to secure your application to protect it against
various security threats. We can follow few best practices in our ExpressJS app to enhance the security of our
application.
Keep Dependencies Updated: Regularly update your project dependencies, including ExpressJS and other npm
packages.<br/>Use Helmet Middleware: The helmet middleware helps secure your application by setting various
HTTP headers. It helps prevent common web vulnerabilities.<br/>Set Secure HTTP Headers: Configure your
application to include secure HTTP headers, such as Content Security Policy (CSP), Strict-Transport-Security
(HSTS), and others.<br/>Use HTTPS: Always use HTTPS to encrypt data in transit. Obtain an SSL certificate for your
domain and configure your server to use HTTPS.<br/>Secure Database Access: Use parameterized queries or
prepared statements to prevent SQL injection attacks. Ensure that your database credentials are secure and not
exposed in configuration files.<br/>40. What is Express router() function?<br/>The [Link]() function is used
to create a new router object. This function is used when you want to create a new router object in your program to
handle requests.
[Link]( [options] )<br/>41. What are the different types of HTTP requests?<br/>The primary HTTP methods
are commonly referred to as CRUD operations, representing Create, Read, Update, and Delete. Here are the main
HTTP methods:
GET: The GET method is used to request data from a specified resource.<br/>POST: The POST method is used to
submit data to be processed to a specified resource.<br/>PUT: The PUT method is used to update a resource or
create a new resource if it does not exist.<br/>PATCH: The PATCH method is used to apply partial modifications to a
resource.<br/>DELETE: The DELETE method is used to request that a specified resource be removed.<br/>42. Do
Other MVC frameworks also support scaffolding?<br/>The Scaffolding technique is supported by other MVC
frameworks also which includes- Ruby on Rails, OutSystems Platform, Play framework, Django, MonoRail, Brail,
Symfony, Laravel, CodeIgniter, YII, CakePHP, Phalcon PHP, Model-Glue, PRADO, Grails, Catalyst, Seam
Framework, Spring Roo, [Link], etc.
43. Which are the arguments available to an ExpressJS route handler function?<br/>In ExpressJS route handler
function, there are mainly3 arguments available that provide useful information and functionality.
req: This represents the HTTP request object which holds information about the incoming request. It allows you to
access and manipulate the request data.<br/>res: This represents the HTTP response object which is used to send
the response back to the client. It provides methods and properties to set response headers, status codes, and send
the response body.<br/>next: This is a callback function that is used to pass control to the next middleware function in
the request-response cycle.<br/>44. How can you deal with error handling in ExpressJS?<br/>ExpressJS provides
built-in error-handling mechanism with the help of the next() function. When an error occurs, you can pass it to the
next middleware or route handler using the next() function. You can also add an error-handling middleware to your
application that will be executed whenever an error occurs.
45. What is the difference between a traditional server and an ExpressJS server?<br/>Feature
Traditional Server (PHP, Java, .NET)
ExpressJS Server (NodeJS)
Language
Uses languages like PHP, Java, C#, Python.
Uses JavaScript (NodeJS).
Architecture
Multi-threaded, blocking I/O.
Single-threaded, non-blocking I/O.
Performance
Slower due to thread-based handling.
Faster due to event-driven, async processing.
Routing Mechanism
Routing is predefined and handled differently for each language.
ExpressJS provides a built-in and flexible routing system.
Used For
Enterprise applications, legacy systems, large-scale applications.
APIs, SPAs, microservices, real-time applications.
46. What is the purpose of the next() function in ExpressJS?<br/>The next() function is used to pass control from one
middleware function to the next function. It is used to execute the next middleware function in the chain. If there are no
next middleware function in the chain then it will give control to router or other functions in the app. If you don't call
next() in a middleware function, the request-response cycle can be terminated, and subsequent middleware functions
won't be executed.
47. What is the difference between [Link]() and [Link]() in ExpressJS?<br/>Feature
[Link]()
[Link]()
Purpose
Defines multiple HTTP methods (GET, POST, PUT, etc.) for a single route.
Mounts middleware or routers to handle requests.
Middleware Support
Does not apply middleware; only handles route-specific logic.
Used to apply middleware functions like authentication, logging, or parsing request bodies.
Routing Scope
Specific to a single route.
Can apply to multiple routes or all requests.
Example Usage
javascript [Link]('/user') .get((req, res) => [Link]('GET User')) .post((req, res) => [Link]('POST User'))
.put((req, res) => [Link]('PUT User'));
javascript [Link]('/user', (req, res, next) => { [Link]('Middleware for /user'); next(); });
Used For
When multiple HTTP methods need to be handled for the same path.
When applying middleware globally or to a group of routes.
48. Explain what dynamic routing is in ExpressJS.<br/>Dynamic routing in ExpressJS include parameters, which
allows you to create flexible and dynamic routes in your web application. This parameters are used in your route
handlers to customize the behaviour based on the data provided.
In Express, dynamic routing is achieved by using route parameters, denoted by a colon (:) followed by the parameter
name.
Here's a simple example:
const express = require('express');<br/>const app = express();
// Dynamic route with a parameter<br/>[Link]('/users/:userId', (req, res) => {<br/> const userId =
[Link];<br/> [Link](`User ID: ${userId}`);<br/>});
// Start the server<br/>const port = 8000;<br/>[Link](port, () => {<br/> [Link](`Server is listening on port
${port}`);<br/>});<br/>49. How to serve static files in ExpressJS?<br/>In ExpressJS, you can serve static files using
the built-in [Link] middleware. This middleware function takes the root directory of your static files as an
argument and serves them automatically.
50. What is the use of [Link]() in ExpressJS?<br/>[Link]() is used to add middleware functions in an Express
application. It can be used to add global middleware functions or to add middleware functions to specific routes.