HTTP Requests in Hapi using Wreck plugin

hapi nodejs Tutorials wreck


Wreck is Javascript library from Hapi-ecosystem to use HTTP requests. Basically it’s uses for Hapi.js projects. You can use it to write async/await code, because it’s promise-based library.


Wreck can be installed using NPM:

npm i wreck

or YARN:

yarn add wreck

Сreating a simple HTTP request

const Wreck = require('wreck');

const example = async function () {
    const res = await Wreck.request('get', '');
    const body = await, {
        json: true

try {
} catch (e) {

The first argument of Wreck.request() it’s the HTTP-method. It supports all popular: GET, POST, PUT, DELETE, default is GET. The second argument - the URI of the requested resource. The third - options object. Also, we can use the next methods to make specified requests:

  • Wreck.get()
  • Wreck.put()
  • Wreck.delete()
  • Wreck.patch()

Getting JSON

To get JSON using Wreck we can use the json property of options object in .get method. We need to set it to true value:

const { res, payload } = await Wreck.get('', {

The console will display:

{ userId: 1,
  id: 1,
  title: 'delectus aut autem',
  completed: false }

To make request with query params, you can use the .payload property:

const { res, payload } = await Wreck.get('', {

The querystring can be generated using the qs module.

Making POST request with payload

We can make POST request with JSON payload in two ways:

const data = JSON.stringify({ a: 1, b: 2 });
const { res, payload } = await'', {
    payload: data

or using the request function:

const data = JSON.stringify({ a: 1, b: 2 });
const { res, payload } = await Wreck.request('post', '', {
    payload: data

If your app keeps the Promises-style of code, you can easily use the following:

Wreck.get('', {json: true})
.then(res => console.log(res.payload))
.catch(err => console.log(err));

Setting custom header

The request headers object can be set in options parameter:

const headers = {
    'Content-Type': 'application/json'
const { res, payload } = await Wreck.request('get', '', {

Setting defaults

To make default headers, agents and other request/read objects, we can create a new instance of Wreck using the Wreck.defaults() method.

const wreck = Wreck.defaults({
    agents: {
        http: new Http.Agent({
            maxSockets: 10
    headers: {
        'Content-Type': 'application/json'
const { res, payload } = await Wreck.get('');

It’s useful if you need to create multiple HTTP clients with different default data.

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus