Everyone and their uncle is writing Facebook applications for the new Facebook Platform. I, too, have my own offering, written by myself and the other OpenHive guys: Bookshelf. Even though the platform was released almost a month ago there are still plenty of tricks, gotchas, and other undocumented oddities that deserve to be brought to light.

Gotchas, tips, and tricks

  1. The Timeout

    For those who know what I'm talking about already the answer is 12 seconds. Everyone else read on.

    Facebook canvas pages (URLs of the form http://apps.facebook.com/yourapp/foo) work on a proxy model. In the application configuration you specify a callback URL so that when someone visits http://apps.facebook.com/yourapp/foo Facebook in turn requests http://mydomain.com/myapp/foo. Facebook fetches the FBML from your callback URL and renders it on the canvas page.

    If your callback takes too long to respond Facebook spits out this ugly message:

    There are still a few kinks Facebook and the makers of <application name> are trying to iron out. We appreciate your patience as we try to fix these issues. Your problem has been logged - if it persists, please come back in a few days. Thanks!

    Ignore the fact that this error message is awful (try back in a few days?!), for now. I did some testing (i.e., a PHP file and a call to sleep) and found that the timeout is set to around 12 seconds. Although it should never, ever take this long to render any webpage, if you're doing a lot of processing you might run afoul of this limit, so watch out.

  2. The Load

    Because canvas pages work on a proxy model your servers will have to handle the load Facebook throws at it. For some apps, like iLike, this means growing from zero to three million users in a week. If you plan on creating a popular app then you'll need to plan and benchmark for high concurrency situations.

    To start you should make sure your database is well optimized. Read my article on MySQL optimization tips for some ideas of what that means — most of the tips are database neutral.

    Second you should use a tool like ab with the concurrency set high and try to maximize your requests served per second. In short, if you're going to be hosting a popular Facebook application be prepared to deal with Facebook-magnitude loads.

  3. The Session

    Before you can talk with Facebook you must initialize a session using the Facebook class provided by the Facebook API library. You cannot tell if the session is valid by whether the session_key field in your object is null — sometimes it looks completely valid but has actually expires. The REST client will throw an exception if you try to do anything with an invalid session, so it's something to avoid.

    You can get your session data you can call auth_getSession(). It returns an array that contains the timeout so you can check directly if the session has expired. If the timeout is set to 0 then the session lasts forever. You can also use try/catch to make sure your sessions are valid:

    $fbuid = $facebook->get_loggedin_user();
    if ($fbuid) {
        try {
            if ($facebook->api_client->users_isAppAdded()) {
                // The user has added our app
            } else {
                // The user has not added our app
            }
       
        } catch (Exception $ex) {
            //this will clear cookies for your app and redirect them to a login prompt
            $facebook->set_user(null, null);
            $facebook->redirect($_SERVER['SCRIPT_URI']);
            exit;
        }
    } else {
        // The user has never used our app
    }

    The above will guarantee that you always have a valid session. (Thanks to Aditya for information about session expiration.)

  4. The JS

    The Facebook Platform supports three means of dynamic, client-side content: iframes, flash, and javascript wrappers. By using iframes you are essentially given free reign to do what you will. Flixster uses Javascript in an iframe to create its UI elements, for example.

    Flash is flash and can be embedded using the fb:swf FBML tag. The Javascript wrappers, however, are where the gotchas pop up. Facebook supports three pieces of Javascript functionality: showing a DOM element, hiding a DOM element, and replacing the contents of a DOM element with HTML returned from a remote URL.

    You can show, hide, or toggle an element with id foo by giving an element clicktoshow, clicktohide, or clicktotoggle attributes with the value foo, respectively.

    To swap out the content of an element with remote content use clickrewriteurl and clickrewriteform. The first parameter contains the URL and the second parameter is the id for a form element containing parameters to pass to the URL. You can combine clicktoshow, clicktohide, and clicktotoggle in a single element but cannot combine these with clickrewriteurl.

    To get around this you can mark it up as follows:

    <div clickrewriteurl="your_url">
        <a href="#" clicktoshow="id_to_show">Click me!</a>
    </div>
     

    This is useful to, for example, show a progress indicator or "Saving…" text as you process something asynchronously. Make sure to test this in all major browsers since I've seen this fail in IE under circumstances.

  5. Using Lighttpd

    lighttpd is an increasingly popular webserver. It is much lighter than Apache at the expense of Apache's modularity and extensibility. A common scenario would be to use it for serving static content.

    However, many people are using it in place of Apache as a full, dedicated webserver. The problem arises when you try to submit large amounts of data via POST to a Facebook canvas page. If the data is large enough Facebook will send your app an Expect: 100-continue header, which lighttpd doesn't understand. This results in lighttpd throwing an HTTP 417 error (pretty obscure, eh?), which Facebook spits right back in the users face.

    To get around this you need to either use something besides lighttpd which does support the 100-continue header (e.g., Apache) or submit the data directly to your server and then redirect to the Facebook after the data is processed.

The Facebook Platform is still young and changes weekly. Keeping abreast of the changes can be daunting, so let me know if this helped at all.

18 Comments

  1. Ramani June 20th, 2007 / 12:11 am

    Useful. thanks!

  2. Aditya June 20th, 2007 / 1:30 am

    I’d like to correct you on the session key part.

    A session is initialised by using the ‘auth_getSession()’ function of the ‘FacebookRestClient’ class. The return is an array which has three keys, one of them being the session key, and the last being the expire time in a Unix timestamp. If this is ‘0′, then it’s an infinite session … else the timestamp tells us when it expires.

    People who have added the application always have an infinite session key :)
    Good list :P Sweet blog!

    Chow!

  3. Eric June 20th, 2007 / 12:06 pm

    iLike had a couple million of users before facebook platform launched.

  4. poitch June 20th, 2007 / 12:24 pm

    Aditya: auth_getSession on the post-add callback URL in most cases throws an Invalid Parameter Exception, and no it’s not some kind of typo when passing the auth token since 5% of the time the same code does manage to retrieve a session. Bottom line I would not rely on this to retrieve the information.

    Regarding timeouts, that’s a good point, but also in a lot of cases I’m getting the also famous the app did not respond problem when my server(s) are not even getting hit by facebook, not sure what the problem is there, the DNS have a pretty long TTL/Refresh if anybody knows that would be great.

  5. Pragmatic Yankee · links for 2007-06-20 June 20th, 2007 / 3:32 pm

    […] 5 Facebook Application Gotchas | 20bits (tags: facebook api programming social) […]

  6. Aditya June 21st, 2007 / 4:25 am

    @Poitch: I’ve never had that exception when I’ve swapped the auth_token for the session_key immediately after hitting the callback URL from the login page. The auth_token expires fairly quickly, so it’s better to swap it as soon Facebook redirects to your callback, which is also what Facebook tells us to do in the documentation :P

  7. Ari Steinberg June 22nd, 2007 / 6:23 pm

    Nice article. I was wondering about your issue #5 - we took a shot at fixing the lighttpd header issue last week. Can you verify that this is still a problem?

    Also, I’d add to your tips that it’s probably worthwhile to subscribe to the Platform Status feed at http://www.facebook.com/feeds/api_messages.php in order to help you keep up with our changes. Thanks!
    -Ari

  8. mobmash blog » Blog Archive » links for 2007-07-04 July 3rd, 2007 / 6:23 pm

    […] 5 Facebook Application Gotchas | 20bits (tags: php facebook api programming) […]

  9. Resources on How to Write a Facebook Application July 28th, 2007 / 8:19 pm

    […] 5 Facebook Application Gotchas […]

  10. del.icio.us bookmarks for August 7th through August 8th » nonsmokingarea.com » Blog Archive August 8th, 2007 / 6:29 pm

    […] 5 Facebook Application Gotchas | 20bits - […]

  11. Olkenava » 5 Facebook Application Gotchas November 8th, 2007 / 11:02 am

    […] read more | digg story […]

  12. NACeqkok December 13th, 2007 / 4:56 am

    smell
    smell

  13. Shalini December 18th, 2007 / 6:30 am

    Hey!
    Great tips on FB.. good to have a list to watch for…
    Well i decided to go with PHP and have the makings of an app!
    I’m facing an error though and if you could point me to a solution, it’ll be very nice.

    Call to a member function on a non-object in facebookapi_php4_restlib.php on line 1397 is what i get. And its really upsetting because i got the same error on a call to two things:
    1. $facebook->api_client->profile_setFBML
    2.facebook->api_client->feed_publishActionOfUser($feed_title,$feed_body);

    I have put this up on the facebook developer forum but no real replies there. You seemed to have comfortably used api_client calls well, so please guide me.

    Thanks in advance

  14. Jason December 21st, 2007 / 1:13 am

    Hi we are trying to get a flash API on Facebook but are having some problems. We are after an example of a Facebook API in AS3.0

  15. Tools For Facebook News » Archive » Facebook Gotchas, tips and tricks February 25th, 2008 / 8:30 am

    […] this site you will find some Gotchas, tips and tricks […]

  16. social media March 4th, 2008 / 1:07 pm

    hey, this is great information have any more websites that i can go to for more great info? thanx

  17. More Facebook Application Gotchas | 20bits April 15th, 2008 / 2:12 am

    […] This is a continuation of my previous article, 5 Facebook Application Gotchas. […]

Leave a Reply