Most Asked Interview Questions for Back End Engineer in 2023

"Preparing for a Successful Back End Engineer Interview: Key Questions and Strategies for 2023"

If you are preparing for a job interview as a Back-end developer, this blog is the perfect place to start. Here, we will provide you with the most commonly asked interview questions and answers related to the Node stack.

In this blog, we will cover topics related to Back-end development such as Node.js and Express.js.This blog will be all about related to Nodejs.

Whether you're a beginner just starting your journey into Back-end development or an experienced developer looking to brush up on your skills before an interview, this blog is the perfect place to start. So, let's dive in and explore the most commonly asked interview questions of Back-end developers together!

Most Asked Interview Questions for Back-end Engineer

1. What is Node.js and how it works?

Node.js is a virtual machine that uses JavaScript as its scripting language and runs Chrome’s V8 JavaScript engine. Basically, Node.js is based on an event-driven architecture where I/O runs asynchronously making it lightweight and efficient.

2. What are some commonly used timing features of Node.js?

  • setTimeout/clearTimeout – This is used to implement delays in code execution.

  • setInterval/clearInterval – This is used to run a code block multiple times.

setImmediate/clearImmediate – Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the event loop.

3. What are the advantages of using promises instead of callbacks?

The main advantage of using promise is you get an object to decide the action that needs to be taken after the async task completes. This gives more manageable code and avoids callback hell.

4. Why is Node.js single-threaded?

Node.js was created explicitly as an experiment in async processing. This was to try a new theory of doing async processing on a single thread over the existing thread-based implementation of scaling via different frameworks.

5. Explain REPL in the context of Node.js?

REPL in Node.js stands for Read, Eval, Print, and Loop. It represents a computer environment such as a window console or Unix/Linux shell where any command can be entered and then the system can respond with an output. Node.js comes bundled with a REPL environment by default. REPL can perform the below-listed tasks:

  • Read: Reads the user’s input, parses it into JavaScript data-structure and then stores it in the memory.

  • Eval: Receives and evaluates the data structure.

  • Print: Prints the final result.

Loop: Loops the provided command until CTRL+C is pressed twice.

6. Explain the purpose of ExpressJS package?

Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications. It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development. Express.js is developed on the middleware module of Nodejs called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.

7. What is MiddleWare in Nodejs and implement it using Express

middleware in Node.js is a function that sits between the server and the route handling functions, allowing you to perform additional processing on requests and responses before they reach their final destination.

Here's a code example:

// Logger middleware function
const logger = (req, res, next) => {
  console.log(`${new Date().toISOString()}: ${req.method} ${req.url}`);
  next(); // call the next middleware function in the chain
}

// Register middleware globally
app.use(logger);

// Route handling function
app.get('/', (req, res) => {
  res.send('Hello World!');
});

8. How do you handle Async Operations in nodejs?

In Node.js, asynchronous operations are typically handled using callbacks, promises, or async/await.

Callbacks: Callbacks are functions that are passed as arguments to another function and are executed once that function completes its operation. In Node.js, callbacks are commonly used for asynchronous operations, such as reading or writing files, making HTTP requests, or connecting to a database. For example, the fs.readFile() function in Node.js takes a callback function as its second argument, which is called when the file is read:

const fs = require('fs');

fs.readFile('myfile.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Promises: Promises are objects that represent the eventual completion or failure of an asynchronous operation and allow you to handle the result or error once the operation is completed. In Node.js, many asynchronous functions return promises by default, and you can also create your own promises using the Promise constructor. For example, the axios library for making HTTP requests returns a promise:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

Async/await: Async/await is a newer syntax that allows you to write asynchronous code that looks synchronous. It is essentially a syntax sugar for working with promises. With async/await, you can use the await keyword to pause the execution of a function until a promise is resolved, and you can use try/catch to handle errors. For example:

const axios = require('axios');

async function getData() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response.data);
  } catch (error) {
    console.log(error);
  }
}

getData();

9. What is the difference between require() and import statements in Node.js?

require() is a function used in Node.js to load modules, while import is a statement introduced in ES6 for loading modules in JavaScript. require() is synchronous and loads modules at runtime, while import is asynchronous and loads modules at compile time. Additionally, import allows you to selectively import only the parts of a module that you need, whereas require() loads the entire module.

10. How do you create a server in Node.js with and without express?

Without Express

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello, World!');
  res.end();
});

server.listen(8080, () => {
  console.log('Server running on port 8080');
});

With Express

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(8080, () => {
  console.log('Server running on port 8080');
});

11. How do you debug Nodejs Applications?

You Can Debug any nodejs application using these methods: -

  1. Console logging: The simplest way to debug a Node.js application is by using console.log() statements to print out variable values, function calls, and other useful information to the console. This is a useful technique for quickly identifying problems and understanding the flow of execution.

  2. Node.js debugger: Node.js comes with a built-in debugger that you can use to step through your code, set breakpoints, and inspect variables. You can start the debugger by running your Node.js application with the --inspect flag and then connecting to it using a debugger client such as Chrome DevTools or Visual Studio Code.

  3. Third-party debuggers: There are several third-party debuggers available for Node.js, such as Node Inspector and ndb. These tools provide a more user-friendly interface than the built-in debugger and can help you debug complex applications more easily.

  4. Profiling: Node.js includes several built-in profiling tools that you can use to identify performance bottlenecks in your application. These tools allow you to collect CPU profiles, heap snapshots, and other types of performance data that can help you optimize your code.

  5. Error handling: Node.js provides several built-in error handling mechanisms, such as try/catch blocks and error events. By properly handling errors in your application, you can make it easier to debug problems and prevent them from causing your application to crash.

12. What is restFUL API in Nodejs ?

A RESTful API in Node.js is an implementation of a web service that follows the REST (Representational State Transfer) architectural style. It uses HTTP methods like GET, POST, PUT, and DELETE to manipulate resources identified by URIs (Uniform Resource Identifiers). A RESTful API in Node.js uses a request-response model, where clients send requests to the server to retrieve or modify resources, and the server sends back responses containing the requested data. The responses are usually formatted in JSON or XML. RESTful APIs in Node.js are widely used for building scalable and modular web applications.

13. Create a restFUL API in nodejs

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

let todos = [
  { id: 1, title: 'Learn Node.js', completed: false },
  { id: 2, title: 'Build a RESTful API', completed: false },
];

app.get('/todos', (req, res) => {
  res.json(todos);
});

app.post('/todos', (req, res) => {
  const todo = req.body;
  todo.id = todos.length + 1;
  todos.push(todo);
  res.status(201).json(todo);
});

app.put('/todos/:id', (req, res) => {
  const id = req.params.id;
  const todo = todos.find(todo => todo.id == id);
  todo.completed = req.body.completed;
  res.json(todo);
});

app.delete('/todos/:id', (req, res) => {
  const id = req.params.id;
  todos = todos.filter(todo => todo.id != id);
  res.status(204).send();
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

In this example, we create a simple API for managing todo items. We define four routes using the get(), post(), put(), and delete() methods of the Express application object.

The get() method is used to retrieve a list of todos from the server. The post() method is used to create a new todo item. The put() method is used to update an existing todo item. The delete() method is used to delete a todo item.

We use the json() middleware to parse incoming JSON data in the request body. We also use the params object to retrieve the id parameter from the URL.

In each route, we use the res object to send a response back to the client. We use the json() method to send JSON

14. How would you handle authentication and authorization in a Node.js application?

Authentication and authorization are essential parts of any web application, including those built with Node.js. Here are some common approaches to handle authentication and authorization in a Node.js application:

  1. Session-based authentication: In this approach, user credentials are stored in a server-side session, and a session ID is sent to the client in a cookie. The server validates the session ID with each request to authenticate the user. The authorization is usually handled by implementing access control rules in the server-side code.

  2. Token-based authentication: In this approach, users authenticate by exchanging a username and password for a token, such as a JSON Web Token (JWT). The token is then sent with each subsequent request to authenticate the user. Authorization can be handled by including user roles or permissions in the token payload and checking them on the server-side.

  3. OAuth2: OAuth2 is a protocol that allows users to authenticate with third-party services, such as Facebook or Google, and then use those credentials to access protected resources on your application. OAuth2 requires setting up a server to handle authentication requests and token exchanges between your application and the OAuth2 provider.

  4. Passport.js: Passport.js is a popular authentication middleware for Node.js that supports various authentication strategies, including session-based, token-based, and OAuth2. It provides a consistent and modular interface for handling authentication and authorization in Node.js applications.

Overall, the best approach to authentication and authorization in a Node.js application depends on the specific requirements of your application.

15. Implement authorization Example with passport.js and Mongodb

const express = require('express');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const User = require('./models/user');

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true });

// Middleware
app.use(bodyParser.json());
app.use(passport.initialize());

// Define a JWT strategy for token-based authentication
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'secret',
};
passport.use(new JwtStrategy(jwtOptions, (payload, done) => {
  User.findById(payload._id, (err, user) => {
    if (err) { return done(err, false); }
    if (user) { return done(null, user); }
    else { return done(null, false); }
  });
}));

// Routes
app.post('/api/login', (req, res) => {
  const { email, password } = req.body;
  User.findOne({ email: email }, (err, user) => {
    if (err) { return res.status(500).json({ message: err.message }); }
    if (!user) { return res.status(401).json({ message: 'Authentication failed. User not found.' }); }
    if (!user.comparePassword(password)) { return res.status(401).json({ message: 'Authentication failed. Wrong password.' }); }

    const token = jwt.sign({ _id: user._id }, 'secret');
    return res.json({ token: token });
  });
});

app.get('/api/protected', passport.authenticate('jwt', { session: false }), (req, res) => {
  return res.json({ message: 'Protected resource' });
});

// Start the server
app.listen(port, () => console.log(`Server listening on port ${port}`));

16. How would you handle database migrations in a Node.js application?

Database migrations are a critical part of database management and are important to ensure that your application's database remains up to date with the latest schema changes. Here's an example of how you can handle database migrations in a Node.js application using a package called migrate-mongo:

  1. Install the migrate-mongo package:
npm install -g migrate-mongo
  1. Create a migrations directory at the root of your project and initialize the migration tool:
migrate-mongo init
  1. Define your first migration script in the migrations directory:
module.exports = {
  async up(db, client) {
    // Perform migration here
  },

  async down(db, client) {
    // Rollback migration here
  }
};

The up function should contain the code for applying the migration, while the down function should contain the code for rolling back the migration.

  1. Run the migration using the migrate-mongo command:
migrate-mongo up

This will apply any pending migrations. You can also use the down command to rollback a migration.

  1. You can also create a new migration script using the create command:
migrate-mongo create my-new-migration

This will create a new migration script in the migrations directory.

  1. Finally, you can integrate database migrations into your Node.js application using a task runner like gulp or grunt. Here's an example using gulp:
const gulp = require('gulp');
const migrateMongo = require('migrate-mongo');

gulp.task('migrate-mongo', async () => {
  const dbConfig = {
    mongodb: {
      url: 'mongodb://localhost:27017/myapp',
    },
    migrationsDir: 'migrations',
  };

  const migration = new migrateMongo(dbConfig, 'migrations');
  await migration.run();
});

This task will run the migrations defined in the migrations directory. You can run this task as part of your build process or manually when you need to apply database migrations.

Overall, migrate-mongo provides a simple and flexible way to handle database migrations in a Node.js application. By integrating it into your build process, you can ensure that your application's database schema is always up to date.


In 2023, the most frequently asked interview questions for a Back End Engineer position typically focus on the candidate's experience with core technologies like databases, servers, and programming languages, as well as their ability to design and optimize scalable and secure systems. Additionally, soft skills such as teamwork, communication, and problem-solving are also highly valued in this role. It is essential for candidates to prepare and demonstrate their expertise in these areas to succeed in the interview process.

Did you find this article valuable?

Support Piyush Yadav by becoming a sponsor. Any amount is appreciated!