The Sunnah regarding visits to Muslim graves is akin to offering the funeral prayer for them before burial. Allah Most High says in His Book concerning the hypocrites:
“Never offer prayer for any of them who dies, nor stand by his grave.”
The implied contrast indicates that funeral prayers are to be offered for believers and that one may stand by their graves.
The Prophet, may Allah bless him and grant him peace, taught his Companions to say when visiting graves:
“Peace be upon you, inhabitants of the abode of believers. Allah willing, we shall join you. May Allah have mercy on those among us and you who have gone before, and those who come after. We ask Allah for well-being for ourselves and for you. O Allah, do not deprive us of the reward on their account, do not subject us to trials after them, and forgive us and them.”
This is because one of the greatest causes of idol worship was revering graves through acts of worship and the like. Allah Most High says in His Book:
“They said, ‘Do not abandon your gods; do not abandon Wadd, Suwā‘, Yaghūth, Ya‘ūq, or Nasr.’”
A group of the early generations said: These were the names of righteous men. When they died, people devoted themselves to remaining at their graves, then fashioned images of them and worshipped those images.
For this reason, the scholars agree that anyone who greets the Prophet, may Allah bless him and grant him peace, at his grave must neither rub his burial chamber nor kiss it. Kissing and touching are reserved for the corners of Allah’s Sacred House; the house of a created being must not be treated like the House of the Creator. Likewise, it is the houses of Allah that are to be sought for circumambulation, prayer, and gatherings for worship: the mosques that Allah has permitted to be raised and His name to be mentioned therein. The houses of created beings must not be sought out and made places of recurring gatherings, as he, may Allah bless him and grant him peace, said:
“Do not make my house a place of recurring gatherings.”
All this is to establish