Sling Academy
Home/Node.js/Using res.end() and res.send() in Express JS

Using res.end() and res.send() in Express JS

Last updated: December 28, 2023

When building web applications with Express JS, a common task is to send responses back to the client. res.end() and res.send() are two fundamental methods provided by the response object in Express to accomplish this. This tutorial provides an overview of how to use these methods effectively, with examples ranging from basic to advanced use cases.

Understanding res.end()

The res.end() method is used to end the response process without any data. It is a Node.js response method, inherited by Express. This method tells the server that you have finished handling the response and that the server should consider this message complete. The syntax looks as follows:

res.end([data[, encoding]])

It is worth noting that when you call res.end(), no more data can be written to the response.

Basic Example – res.end()

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

Understanding res.send()

The res.send() method is an Express-specific method that sends a response of various types to the client. It is actually more powerful than res.end() because it can handle different types of data automatically, including applying proper content-type headers. The syntax is:

res.send([body])

This method not only allows you to set the content of the response but also concludes the response process.

Basic Example – res.send()

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

When to Use res.end() and res.send()

res.end() is used when you want to go no further in detail and simply want to end the response, possibly after sending data. res.send() meanwhile can be used for most cases where you need to send processed data back to the client like HTML, JSON, and even files.

Sending JSON – res.send()

app.get('/user', (req, res) => {
  res.send({ name: 'John Doe', age: 30 });
});

Sending HTML – res.send()

app.get('/dashboard', (req, res) => {
  res.send('<h1>Welcome to your Dashboard</h1>');
});

Advanced Use Cases

There are more advanced scenarios where you would want to use these methods in different ways.

Streaming Data

When you want to stream data, you might need to use res.end() to signal that the streaming has finished.

app.get('/stream', (req, res) => {
  res.write('Streaming starts...\n');
  // Stream your data here
  res.end('...Streaming ended.');
});

Handling Errors

When handling errors, you might want to use res.send() to send back an error message with a status code.

app.use((err, req, res, next) => {
  res.status(500).send('Something broke!');
});

Content Negotiation

Express provides ways to do content negotiation out of the box. This example shows how to use req.accepts() to determine the response type.

app.get('/negotiate', (req, res) => {
  if (req.accepts('json')) {
      res.send({ message: 'JSON content' });
  } else if (req.accepts('html')) {
      res.send('<p>HTML content</p>');
  } else {
      res.end();
  }
});

Conclusion

In conclusion, res.end() and res.send() are handy methods for sending responses to clients in Express JS apps. While res.end() is ideal for quickly finishing the response, res.send() gives more flexibility and is suited for most of the content types you will typically send back to your clients. Understanding when and how to use each method allows for better control over the HTTP response and aids in the development of robust web servers.

Next Article: Node.js & Express: Implementing Route Guards with Middleware (3 Ways)

Previous Article: How to Download a File from NodeJS Server using Express

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates