Hyprlock on Laptop Lid closing

I fail to get hyprlock to run reliably. I use hyprland on Arch Linux.

When closing my laptop lid, the system suspends, and opening the lid resumes the session. I tried writing a systemd service to run before any sleep state, that would execute hyprlock. When done as a regular system service, it complains that hyprlock can not be executed by the root user. If done like the Arch Wiki recommends, it complains that some Environment variables are missing, and I don’t think I can provide them.

I am very confused about what is happening. I also tried using hypridle to lock before sleep, which works fine for regular suspends (as in systemctl suspend), but not when closing the laptop lid.

This is my systemd service /etc/systemd/system/[email protected]

[Unit]
Description=Lock Screen before going to sleep using hyprlock
Before=sleep.target

[Service]
User=%I
Type=oneshot
ExecStart=/usr/bin/hyprlock
ExecStartPost=/usr/bin/sleep 1

[Install]
WantedBy=sleep.target

I enable it with systemctl enable hyprlock@madcat, where madcat is my username. I test it with systemctl start hyprlock@madcat. The logs as printed by systemctl status read:

Nov 15 23:08:47 madcat hyprlock[3264]: error: XDG_RUNTIME_DIR is invalid or not set in the environment.
Nov 15 23:08:47 madcat systemd[1]: [email protected]: Main process exited, code=dumped, status=6/ABRT
Nov 15 23:08:47 madcat systemd[1]: [email protected]: Failed with result 'core-dump'.

I don’t think I can provide the XDG_RUNTIME_DIR in a sensible manner, can I?

I can’t seem to find anyone struggling with getting this very simple feature working, so please tell me what I am missing.

If you use hypridle, you can just add

general {
    lock_cmd = pidof hyprlock || hyprlock       # avoid starting multiple hyprlock instances.
    before_sleep_cmd = loginctl lock-session    # lock before suspend.
}

If not, try using a user service instead (not sure if that supports Before=sleep.target though). It should have the correct env variables if hyprland is managed with uwsm.

but not when closing the laptop lid.

Did you modify /etc/systemd/logind.conf in any way? Works fine for me on defaults

Hi.

I had a similar issue earlier. I use this:

#lock the screen and suspend when close the lid
bindl=,switch:on:Lid Switch, exec, hyprlock & systemctl suspend

just add it to the hyprland.conf. This works for me on 2 laptop and 2 different systems ( Garuda-Hyprland, Omarchy )