CORS on DataSnap REST Server

Cross-origin resource sharing (CORS) is a mechanism that enables resources to be shared across domains. Typically this isn’t allowed to prevent security issues. To enable on your DataSnap REST server you can use the following code per MVP Nirav Kaku from India.

All you need to do is add a custom header in the Response before dispatching the result on the DataSnap server…

procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject;<br />
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);<br />
begin<br />
  //allows cross domain calls<br />
  Response.SetCustomHeader('Access-Control-Allow-Origin','*');<br />
  if FServerFunctionInvokerAction &lt;&gt; nil then<br />
    FServerFunctionInvokerAction.Enabled := AllowServerFunctionInvoker;<br />

It is useful for DataSnap server developers who want
their REST calls to be supported via AJAX using JavaScript from a
different server.


Note: CORS is security feature of the browser so there could be some
dependency there. Tested with Firefox, Chrome and IE and it seems to
be working fine.

This entry was posted in News, REST, Source Code. Bookmark the permalink.

6 Responses to CORS on DataSnap REST Server

  1. David Moorhouse says:

    The second parameter in the example, “*”, will allow any third party to access your js code/resources. You can instead restrict access to known domains e.g. “”

  2. Giovanni says:

    About “OPTIONS request” how create this method in DATASNAP Restful?

  3. Giovanni did you find the answer that you are asking for ? I am interested too.

  4. Marc Guillot says:

    This is an incomplete solution, it allows CORS calls but it doesn’t handle CORS OPTION calls to be able to send your session id throught a Pragma Header.

    You just need to add a couple of lines to completely handle COS calls :

    procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);

    if Trim(Request.GetFieldByName(‘Access-Control-Request-Headers’)) ” then begin
    Response.SetCustomHeader(‘Access-Control-Allow-Headers’, Request.GetFieldByName(‘Access-Control-Request-Headers’));
    Handled := True;

    if FServerFunctionInvokerAction nil then
    FServerFunctionInvokerAction.Enabled := AllowServerFunctionInvoker;

  5. Marc Guillot says:

    The comments manager has modified my text, you can find the correct code in this post.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.