The Messenger of Allah ﷺ said, "When one of you enters the mosque, let him send greetings of peace upon the Prophet ﷺ, then say, 'O Allah, open for me the gates of Your mercy.' And when he leaves, let him say, 'O Allah, I ask You of Your bounty.'"
قال رسول الله ﷺ: إذا دخل أحدكم المسجد فليسلم على النبي ﷺ ثم ليقل: اللهم افتح لي أبواب رحمتك، فإذا خرج فليقل: اللهم إني أسألك من فضلك.
Reported by Abu Dawud (465), Ibn Majah (772), and Bayhaqi (2/441–442), and Ibn Hibban graded it sahih (2048), all of them through various routes from Rabia bin Abu Abdul-Rahman, from Abdul-Malik bin Saeed bin Suwayd, from Abu Humayd or Abu Usayd, who related it. Except that Ibn Majah's version does not mention Abu Usayd. Its chain is sahih. Muslim also reported it (713) from Rabia through the same chain, except that his version does not contain the wording about the greeting of peace. However, Bayhaqi said, "The wording about the greeting of peace is preserved in it," meaning even though it does not appear in Sahih Muslim.It is established that Kaab Ahbar said, "Abu Hurairah, remember two things from me, I advise you with them. When you enter the masjid, invoke blessings upon the Prophet ﷺ and say, 'O Allah, open for me the doors of Your mercy.' And when you leave the masjid, invoke blessings upon the Prophet ﷺ and say, 'O Allah, protect me from Satan.'" This was reported by Nasai in Amal al-Yawm wal-Layla (91) with a good chain. It has also been reported as a raised hadith, but the correct view is that it is a stopped report, as is explained in detail in the book on prayer.Invoking blessings upon the Prophet ﷺ upon entering and leaving the masjid has also been reported through the hadith of Fatimah, found in Tirmidhi (314) and Ibn Majah (771), but its chain is disconnected.