925 B
925 B
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Environment is browser | browser,node | intermediate | blog_images/travel-mug-3.jpg | 2018-03-19T04:50:55+02:00 | 2020-10-20T23:02:01+03:00 |
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
- Use
Array.prototype.includes()on thetypeofvalues of bothWindowandDocument(globals usually only available in a browser environment unless they were explicitly defined), which will returntrueif one of them isundefined. typeofallows globals to be checked for existence without throwing aReferenceError.- If both of them are not
undefined, then the current environment is assumed to be a browser.
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
isBrowser(); // true (browser)
isBrowser(); // false (Node)