Why are my $messages delayed one page refresh? I have a page with a very simple template:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;TEST REGISTRATION PAGE&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
    &lt;?php 
        print drupal_get_form('user_register');
        print $messages;
        print $closure;
        print $main_content;
    ?&gt;
&lt;/body&gt;&lt;/html&gt;


Basically, it displays the registration form and nothing else.


I enter some bad data on the form &mdash; an already used username (admin), and no email address.
I click "create new account".
The page seems to submit and reload, but nothing has happened &mdash; no error messages are displaying.
I refresh the page (F5).
Firefox displays "to display this page, Firefox must send information that will repeat any action that was performed earlier" &mdash; so I know that my POST went through previously.
I click "resend" in that dialog window.
My error messages appear &mdash; "e-mail address field is required", "the name admin is already taken".


This occurs for all of the forms I've tested so far, not just the registration form.

Why is this happening? What can I do to fix it so that the error messages display the first time?

I'm happy to do whatever I need to do debug this, but I need some direction to start looking in. :)
Most likely the problem is that you are calling the form when the messages already have been created, which is why they don't appear. You need to call the form, earlier in the process of the page being built or get the messages, with drupal_get_messages.

What you really should do it is to create this functionality in a module and theme the page instead, of doing this in your theme. You could potentially run into many more problems like this.