[Linux/NixOS systemd-logind] Don’t suspend/sleep laptop on lid closure when external monitor is connected

systemd’s login manager ( logind ) is responsible for this, and it can be configured via the HandleLidSwitchDocked option in logind.conf (see also man 5 logind.conf).

NixOS

From the available NixOS logind options using services.logind.lidSwitchDocked in /etc/nixos/configuration.nix (see NixOS manual):

# /etc/nixos/configuration.nix
# ...
services.logind.lidSwitchDocked = "ignore";
# ...

(But this is the default, so this will just make it explicit.)

Other Linux distributions

logind.conf usually resides in /etc/systemd/logind.conf and just add the following line:

[Login]
# ...
HandleLidSwitchDocked=ignore