Hey friend,
If you've ever built an automation that syncs data or posts content to a major platform, you've probably faced the classic dilemma: use a headless browser (like Playwright) or wrestle with the official API.
While headless browsers seem easier at first because you don't need developer credentials, they are incredibly fragile. A single CSS class change by the platform's front-end developers breaks your entire script.
For long-term reliability, official APIs are always the better choice. But they come with a specific hurdle: handling OAuth2 token expiration in background cron jobs where no human can click "Allow access."
Here is the simple, bulletproof pattern I use to keep background API connections alive:
* Store the Refresh Token: Access tokens usually expire in an hour. Your database must store the long-lived refresh token securely.
* The "Check & Refresh" wrapper: Before every single API call, check the token's expires_at timestamp. If it is within 5 minutes of expiring, trigger a token refresh request to get a new access token before making the actual API call.
* Handle Token Rotation: Some modern APIs return a new refresh token alongside the new access token. Always update both tokens in your database during the refresh cycle to avoid getting locked out.
Implementing this three-step check saves you from waking up to failed cron jobs.
If you want to see this exact API pattern in action within a video pipeline, I built a tool called YouTube Shorts Automation.
It is a self-hosted script that handles the entire pipeline: writing an AI script, rendering a vertical video with text-to-speech, and uploading it securely via the official YouTube API on your schedule. It is a clean, programmatic starting point for automated video workflows.
