Keep in mind that after setting the cookie (with the session ID, which I'm assuming you're doing), you're not going to receive that cookie in the same request as it's been set.
I'm guessing:
- User logs in
- You set cookie
- You try to display main page
- You check for session ID in cookie
- Cookie not yet set, fail
- User tries again, since this is a new request, the cookie you previously set now is sent to the server and the login succeeds.