WarsawJS

How to create a simple Node.js proxy for third-party APIs

How to create a simple Node.js proxy for third-party APIs

Illarion Khapyorskiy @illarionvk

The problem

Solutions: JSONP vs Proxy

JSONP Proxy with CORS policy
Only GET GET, POST, PUT, DELETE
Results are injected as code
(possible XSS issues)
Results are parsed (more secure)
Indirect error handling Reliable error handling

Hapi logo

Hapi framework

A stable and reliable application framework for Node.js, used in production by Walmart, Yahoo and NPM.

Created by Eran Hammer

Step 1

1 var url = require('url');
2 
3 var Hapi = require('hapi');
4 
5 var Wreck = require('wreck'); // HTTP Client Utilities

Step 2

1 var server = new Hapi.Server();
2 
3 server.connection({
4   port: process.env.PORT || 3000
5 });

Step 3

1 server.method('getInstagram', getInstagram, {
2   cache: {
3     expiresIn: 60 * 60 * 1000,
4     staleIn: 60 * 1000,
5     staleTimeout: 100
6   }
7 });

Step 4

 1 var getInstagram = function(next) {
 2   var instagramURL = 'https://api.instagram.com/...';
 3   Wreck.get(instagramURL, null, function(err, res, payload) {
 4     if (err) { return next(err); }
 5     if (res.statusCode !== 200) {
 6       return next(res.statusCode);
 7     }
 8     return next(null, JSON.parse(payload));
 9   });
10 };

Step 5

 1 server.route({ method: 'GET', path: '/instagram.json',
 2   handler: function(request, reply) {
 3     return server.methods.getInstagram( function(error, result) {
 4       if (error) { return reply({ error: error }).code(500); }
 5       return reply(result);
 6     });
 7   }, config: {
 8     cors: true,
 9     cache: { expiresIn: 60 * 60 * 1000, privacy: 'private' }
10   }
11 });

Final step

1 server.start( function() {
2   console.log('Server running at:', server.info.uri);
3 });

See you next month at WarsawJS

Fork me on Github