Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js readStream.setRawMode() Method
Next article icon

Node response.setHeader() Method

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The response.setHeader() method in Node.js is used to set HTTP headers for a response. It allows you to define one or more headers for the HTTP response sent by the server. If a header with the same name already exists, its value will be replaced. Additionally, headers can be set as an array of values, especially useful for headers like Set-Cookie, which may require multiple values.

Syntax

response.setHeader(name, value)

Parameters: This property accepts a single parameter as mentioned above and described below:

  • name <String>: It accepts the name of the header and it is case-insensitive.
  • value <any>: It can accept any values like objects, string, integer, Array, etc. 

Return Value: This method does not return any value. It simply sets the header as described.

Example 1: In this example, we set a few headers and retrieve them using response.getHeader().

javascript
// Importing the http module const http = require("http");  // Setting up PORT const PORT = process.env.PORT || 3000;  // Creating HTTP server const httpServer     = http.createServer((request, response) => {           // Setting up headers           response.setHeader("Content-Type", "text/html");           response.setHeader(               "Set-Cookie",               [ "type=ninja", "language=javascript" ]);            // Retrieving headers           console.log("When Header is set as a string:",                       response.getHeader("Content-Type"));           console.log("When Header is set as an Array:",                       response.getHeader("Set-Cookie"));            // Printing all set headers           const headers = response.getHeaders();           console.log(headers);            // Sending response           response.writeHead(200);           response.end("ok");       });  // Listening to the HTTP server httpServer.listen(PORT, () => {     console.log(`Server is running at port ${PORT}...`); }); 

Output: Now run http://localhost:3000/ in the browser.

Server is running at port 3000...
When Header is set as a string: text/html
When Header is set as an Array: ['type=ninja', 'language=javascript']
[Object: null prototype]
{ 'content-type': 'text/html', 'set-cookie': ['type=ninja', 'language=javascript']}

Example 2: In this example, various types of headers (string, empty string, number, and array) are set and retrieved.

JavaScript
// Importing the http module const http = require("http");  // Setting up PORT const PORT = process.env.PORT || 3000;  // Creating HTTP server const httpServer = http.createServer((req, response) => {     // Setting different headers     response.setHeader("Alfa", "Beta");     response.setHeader("Alfa1", "");     response.setHeader("Alfa2", 5);     response.setHeader("Cookie-Setup",                        [ "Alfa=Beta", "Beta=Romeo" ]);      // Retrieving specific headers     console.log("When Header is set as an Array:",                 response.getHeader("Cookie-Setup"));     console.log("When Header is set as 'Beta':",                 response.getHeader("Alfa"));     console.log("When Header is set as '':",                 response.getHeader("Alfa1"));     console.log("When Header is set as number 5:",                 response.getHeader("Alfa2"));     console.log("When Header is not set:",                 response.getHeader("Content-Type"));      // Printing all headers     const headers = response.getHeaders();     console.log(headers);      // Sending response to the browser     var Output         = "Hello Geeksforgeeks..., Available headers are:"           + JSON.stringify(headers);     response.write(Output);     response.end("ok"); });  // Listening to the HTTP server httpServer.listen(PORT, () => {     console.log("Server is running at port 3000..."); }); 


Output:

Server is running at port 3000...
When Header is set as an Array: [ 'Alfa=Beta', 'Beta=Romeo' ]
When Header is set as 'Beta': Beta
When Header is set as '':
When Header is set as number 5: 5
When Header is not set: undefined
[Object: null prototype] {
alfa: 'Beta',
alfa1: '',
alfa2: 5,
'cookie-setup': ['Alfa=Beta', 'Beta=Romeo']
}

Output: Now run http://localhost:3000/ in the browser.

Hello Geeksforgeeks..., Available headers are:
{"alfa":"Beta", "alfa1":"", "alfa2":5, "cookie-setup":["Alfa=Beta", "Beta=Romeo"]}ok

Conclusion

The response.setHeader() method in Node.js is a useful way to set HTTP headers for a response. It allows you to add or modify headers before sending the response. For most use cases, it’s better to use setHeader() for progressively adding headers, rather than using writeHead() immediately, as it gives you more flexibility and control over the headers.



Next Article
Node.js readStream.setRawMode() Method
author
amitkumarjee
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Web Technologies
  • Node.js-Methods

Similar Reads

  • Node response.writeHead() Method
    The response.writeHead() property is used to send a response header to the incoming request. It was introduced in Node.js v1.0 and is a part of the 'http' module. The status code represents a 3-digit HTTP status code (e.g., 404), and the headers parameter contains the response headers. Optionally, a
    3 min read
  • Node.js response.write() Method
    The response.write() (Added in v0.1.29) method is an inbuilt Application program Interface of the ‘http’ module which sends a chunk of the response body that is omitted when the request is a HEAD request. If this method is called and response.writeHead() has not been called, it will switch to implic
    3 min read
  • Node.js response.writeContinue() Method
    The response.writeContinue() (Added in v0.3.0) method is an inbuilt Application Programming Interface of the ‘http’ module which sends an HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event on Server. The response.writeContinue(
    2 min read
  • Node.js readStream.setRawMode() Method
    The readStream.setRawMode() method is an inbuilt application programming interface of class ReadStream within 'tty' module which is used to set the raw mode of the Read stream object to work as a raw device. Syntax: const readStream.setRawMode( mode ) Parameters: This method takes the Boolean value
    2 min read
  • Node.js fs.promise.readdir() Method
    The fs.promise.readdir() method defined in the File System module of Node.js. The file System module is basically to interact with the hard disk of the users computer. The readdir() method is used to read the files and folders names. The fs.promise.readdir() method returns a resolved or rejected pro
    2 min read
  • Node.js response.removeHeader() Method
    The response.removeHeader() (Added in v0.9.3) property is an inbuilt property of the ‘http’ module which removes a header identified by a name that's queued for implicit sending. The header name matching is case-insensitive. The object returned by the response.getHeaders() method does not prototypic
    4 min read
  • Node.js Stream.pipeline() Method
    The stream.pipeline() method is a module method that is used to the pipe by linking the streams passing on errors and accurately cleaning up and providing a callback function when the pipeline is done.  Syntax: stream.pipeline(...streams, callback) Parameters: This method accepts two parameters as m
    3 min read
  • Node.js Stream readable.pause() Method
    The readable.pause() method is an inbuilt application programming interface of Stream module which is used to stop the flowing mode from emitting 'data' events. If any data that becomes accessible will continue to exist in the internal buffer. Syntax: readable.pause() Parameters: This method does no
    2 min read
  • Node.js | os.userInfo() Method
    The os.userInfo() method is an inbuilt application programming interface of the os module which is used to get the information of currently effective user. Syntax:  os.userInfo( options ) Parameters: This method accepts single parameter options which is optional parameter. It specifies the process o
    2 min read
  • Node.js response.hasHeader() Method
    The response.hasHeader() (Added in v7.7.0) property is an inbuilt property of the ‘http’ module which returns true if the header identified by name is currently set in the outgoing headers. The header name matching is case-insensitive. The object returned by the response.getHeaders() method does not
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences