Always detect the runtime environment before using environment-specific APIs or utilities. This is crucial for networking applications that may run in browsers, Node.js servers, or cross-platform contexts.
Always detect the runtime environment before using environment-specific APIs or utilities. This is crucial for networking applications that may run in browsers, Node.js servers, or cross-platform contexts.
Key practices:
path.posix.join
for consistent path handling)typeof window !== 'undefined' && 'CSS' in window
before using window.CSS.supports()
)"node:url"
instead of "url"
for Node.js built-ins)Example of proper environment detection:
// Check for browser environment before using browser APIs
if (!this.isServer && typeof window !== 'undefined' && 'CSS' in window) {
this.isViewTransitionTypesSupported = window.CSS.supports(...)
}
// Use Node.js module prefix for built-in modules
import { fileURLToPath } from 'node:url'
// Use platform-specific path utilities
path.posix.join(routesDirectoryFromRoot, v.filePath as string)
This approach prevents runtime errors and ensures your networking code works reliably across different deployment environments.
Enter the URL of a public GitHub repository