There is an npm package just for this and it can be used both on client-side and server-side.
browser-or-node
You can use it in your code like this
import { isBrowser, isNode } from 'browser-or-node';
if (isBrowser) {
// do browser only stuff
}
if (isNode) {
// do node.js only stuff
}
Disclaimer: I am the author of this package :)