Skip to main content
The Response class provides methods for sending HTTP responses, setting headers, cookies, and managing response data.

Importing

import { HttpContext } from '@adonisjs/core/http'

export default class UsersController {
  async index({ response }: HttpContext) {
    // Access response
  }
}

Properties

finished
boolean
Whether the response has been sent
isPending
boolean
Whether the response is pending
headersSent
boolean
Whether headers have been sent

Sending Responses

send()

Send a response body.
response.send('Hello World')
response.send({ message: 'Success' })
response.send(Buffer.from('data'))
body
any
Response body (string, object, buffer, stream)
Returns: void

json()

Send a JSON response.
response.json({ 
  users: [],
  meta: { total: 0 }
})
body
any
Data to serialize as JSON
Returns: void

jsonp()

Send a JSONP response.
response.jsonp({ data: [] })
body
any
Data to serialize as JSONP
callbackName
string
default:"'callback'"
JSONP callback function name
Returns: void

stream()

Stream a response.
const fileStream = fs.createReadStream('video.mp4')
response.stream(fileStream)
stream
ReadableStream
Readable stream to pipe
Returns: void

download()

Download a file.
response.download('storage/invoices/invoice-123.pdf')
filePath
string
Path to the file
fileName
string
Optional filename for download
Returns: void

attachment()

Download a file with a custom name.
response.attachment(
  'storage/reports/report-2024.pdf',
  'Annual Report.pdf'
)
filePath
string
Path to the file
fileName
string
Filename for download
Returns: void

Status Codes

status()

Set the response status code.
response.status(201).json({ created: true })
code
number
HTTP status code
Returns: this

getStatus()

Get the current status code.
const status = response.getStatus()
Returns: number

safeStatus()

Set status code if not already set.
response.safeStatus(200)
code
number
HTTP status code
Returns: this

Status Helpers

ok()

Send a 200 OK response.
response.ok({ message: 'Success' })
body
any
Response body
Returns: void

created()

Send a 201 Created response.
response.created({ user })
body
any
Response body
Returns: void

accepted()

Send a 202 Accepted response.
response.accepted({ jobId: '123' })
body
any
Response body
Returns: void

noContent()

Send a 204 No Content response.
response.noContent()
Returns: void

badRequest()

Send a 400 Bad Request response.
response.badRequest({ error: 'Invalid input' })
body
any
Response body
Returns: void

unauthorized()

Send a 401 Unauthorized response.
response.unauthorized({ error: 'Not authenticated' })
body
any
Response body
Returns: void

forbidden()

Send a 403 Forbidden response.
response.forbidden({ error: 'Access denied' })
body
any
Response body
Returns: void

notFound()

Send a 404 Not Found response.
response.notFound({ error: 'User not found' })
body
any
Response body
Returns: void

methodNotAllowed()

Send a 405 Method Not Allowed response.
response.methodNotAllowed({ error: 'Method not supported' })
body
any
Response body
Returns: void

conflict()

Send a 409 Conflict response.
response.conflict({ error: 'Email already exists' })
body
any
Response body
Returns: void

unprocessableEntity()

Send a 422 Unprocessable Entity response.
response.unprocessableEntity({ errors: validationErrors })
body
any
Response body
Returns: void

internalServerError()

Send a 500 Internal Server Error response.
response.internalServerError({ error: 'Something went wrong' })
body
any
Response body
Returns: void

Redirects

redirect()

Redirect to a URL.
response.redirect('/login')
response.redirect('https://example.com')
response.redirect().back()
url
string
URL to redirect to
statusCode
number
default:"302"
HTTP status code for redirect
Returns: void

redirectToRoute()

Redirect to a named route.
response.redirectToRoute('users.show', { id: 1 })
routeName
string
Name of the route
params
object
Route parameters
options
object
Additional options (qs, domain)
Returns: void

back()

Redirect back to the previous URL.
response.redirect().back()
Returns: void

withQs()

Add query string to redirect.
response.redirect('/search').withQs({ q: 'adonisjs' })
queryString
object
Query string parameters
Returns: this

clearQs()

Clear query string from redirect.
response.redirect().back().clearQs()
Returns: this

Headers

Set a response header.
response.header('X-Custom-Header', 'value')
key
string
Header name
value
string
Header value
Returns: this

append()

Append a value to a header.
response.append('Set-Cookie', 'session=abc')
key
string
Header name
value
string
Header value
Returns: this

removeHeader()

Remove a response header.
response.removeHeader('X-Powered-By')
key
string
Header name
Returns: this

getHeader()

Get a response header value.
const contentType = response.getHeader('Content-Type')
key
string
Header name
Returns: string | string[] | undefined

Content Type

type()

Set the Content-Type header.
response.type('application/json')
response.type('html')
response.type('pdf')
type
string
Content type or file extension
charset
string
Optional character set
Returns: this

vary()

Set the Vary header.
response.vary('Accept-Encoding')
field
string
Header field name
Returns: this

Cookies

Set a signed cookie.
response.cookie('session_id', '123', {
  maxAge: 3600,
  httpOnly: true
})
key
string
Cookie name
value
any
Cookie value
options
CookieOptions
Cookie options
  • maxAge: Max age in seconds
  • httpOnly: HTTP only flag
  • secure: Secure flag
  • sameSite: SameSite policy
  • path: Cookie path
  • domain: Cookie domain
Returns: this

plainCookie()

Set a plain (unsigned) cookie.
response.plainCookie('tracking_id', 'xyz')
key
string
Cookie name
value
any
Cookie value
options
CookieOptions
Cookie options
Returns: this

encryptedCookie()

Set an encrypted cookie.
response.encryptedCookie('sensitive_data', secretValue)
key
string
Cookie name
value
any
Cookie value
options
CookieOptions
Cookie options
Returns: this

clearCookie()

Clear a cookie.
response.clearCookie('session_id')
key
string
Cookie name
Returns: this

Caching

fresh()

Check if the response should be fresh.
if (response.fresh()) {
  response.notModified()
}
Returns: boolean

etag()

Set the ETag header.
response.etag('content-hash')
etag
string
ETag value
weak
boolean
default:"false"
Use weak ETag
Returns: this

notModified()

Send a 304 Not Modified response.
response.notModified()
Returns: void

Example Usage

import { HttpContext } from '@adonisjs/core/http'

export default class UsersController {
  async index({ response }: HttpContext) {
    const users = await User.all()
    
    // JSON response
    return response.json({
      data: users,
      meta: { total: users.length }
    })
  }
  
  async store({ request, response }: HttpContext) {
    const user = await User.create(request.all())
    
    // Created response with location header
    return response
      .status(201)
      .header('Location', `/users/${user.id}`)
      .json({ user })
  }
  
  async download({ response }: HttpContext) {
    // File download
    return response.download('storage/reports/report.pdf')
  }
  
  async redirect({ response }: HttpContext) {
    // Redirect with flash message
    return response
      .redirect()
      .withQs({ success: 'User created' })
      .toRoute('users.index')
  }
}