I have a public Single Page Application (SPA) that is calling my backend REST service via JavaScript. How can I secure the REST service so that it will only accept calls from my SPA and no other clients or users? Basically, my SPA should be the only allowed user of the service.

Any way that I can think to secure it would involving storing some kind of secret, however because the SPA is written completely in JavaScript anyone can view the source.

  • I'd write this in answer with some more explanation, but I wouldn't feel good about it since it's not really an answer. To sum it up for you: You're trying to achieve the impossible. With our current technology (and, frankly, any relevant technology I can imagine), there's no way to do what you're trying to do. The closest thing is restricting your SPA to authenticated users and then generate a short-lived secret for each user that is sent to the browser after login.
    – Adi
    Mar 22, 2014 at 14:12

3 Answers 3


You can't, really. Anything sent via javascript can be tampered with. Because of this your SPA will be vulnerable to XSS and MITM attacks. An option would be using session tokens and obfuscation which is such a grotesque solution. Plus this will be an opening for CSRF attacks: CSRF. Otherwise, I recommend having your users login so that there will be some form of authentication.


I guess its not 100% possible. As per my understanding, what you can give try is using cryptographic nonce. Learn more about nonce at - http://en.wikipedia.org/wiki/Cryptographic_nonce

The simple way I would try to achieve this. 1. Generate an initial nonce. 2. Use this nonce in next communication with the server. 3. At server, verify that the nonce is generated by my application only 4. Create a new nonce and piggy-back it along with the response. 5. Go to step 2 and use the new nonce.


You can configure CORS(Cross origin Resource Sharing) to respond to requests coming from a particular domain. In node JS there is a package to do it.

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://linktoyourSPA.com',


This would allow requests only from that particular domain.

If you are not using nodeJs. You can manually set response header Access-Control-Allow-Origin.for more info read this https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

  • "no other clients" sounds to me like he wants to prevent all other clients, not just javascript coming from other domains. CORS does nothing to prevent trivial crafting of requests with curl or other software. Jul 7, 2018 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.