For modern web applications, it is vital that one can test our SPA applications thoroughly before deployment. More so for SharePoint development, it would be great if we could implement real world data communications with our SharePoint tenant from our local development system, without necessarily deploying to our SharePoint tenant first.

There are times when you might want to test your application against real data in SharePoint, instead of mock data. Wouldn’t is be great if we could have a proxy to send these requests to, and it will take care of all the authentication stuff for us.  

sp-rest-proxy is the tool you should consider if you find yourself in that situation.

So what is sp-rest-proxy? sp-rest-proxy, as the name suggest, is a proxy that provides authentication context to your API calls to SharePoint backend. It sits in between your local dev toolchain and SharePoint tenant.

sp-rest-proxy schema

For example, your local express application can perform API calls to a remote SharePoint instance.

sp-rest-proxy supports

  • SharePoint Online
  • SharePoint On-Prem (2019/2016/2013/2010)

and its able to proxy calls made from

  • REST API
  • CSOM requests
  • SOAP web services
  • Static resources

How do I use it?

1. Install NPM module in the project:
npm install sp-rest-proxy --save-dev

2. Create server.js with the following code:

const RestProxy = require('sp-rest-proxy');

const settings = {
  configPath: './config/private.json', // Location for SharePoint instance mapping and credentials
  port: 8080,                          // Local server port
  staticRoot: './node_modules/sp-rest-proxy/static'               // Root folder for static content
};

const restProxy = new RestProxy(settings);
restProxy.serve();

3. Add npm task for serve into package.json:

"scripts": {
  "serve": "node ./server.js"
}

4. Run npm run serve.

5. Provide SharePoint configuration parameters.

6. Navigate to http://localhost:8080 (or whatever in settings)

sp-rest-proxy test

Configuring for PnP JS

If you are working with PnP JS and SPFx, you can use the below configuration to get you started.

import { Web, sp } from '@pnp/sp';  
import { proxyUrl, webRelativeUrl } from './../settings';  
// settings.ts should be created with corresponding exports

...
let web: Web;  
if (Environment.type === EnvironmentType.Local) {
  // To let PnPjs know which base URL to use:
  sp.setup({
    sp: {
      baseUrl: `${proxyUrl}${webRelativeUrl}`
    }
  });
  // or a Web object should be created with explicit web URL
  web = new Web(`${proxyUrl}${webRelativeUrl}`);
} else {
  // On SharePoint page PnPjs should be configured with
  sp.setup({ spfxContext: this.context });
  // or a Web object should be created with explicit web URL
  web = new Web(this.context.pageContext.web.absoluteUrl);
}
// Then universal pnp code and dealing with SPFx specifics
/*
web.lists.get()  
  .then(...).catch(...);
*/
...