All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad is His slave and Messenger.
Since the mosque is not built on graves and the graves are outside the mosque, whether they are on the right or the left side of the mosque, or behind it, then this does not affect the legitimacy and validity of performing the prayer in it. The wall of the mosque is enough – Allaah willing – to separate between the mosque and the graveyard.
Shaykh Ibn Baaz was asked about a mosque that is surrounded by a graveyard and he answered: “If there are graves in the direction of the Qiblah, then to be on the safe side, it is better to separate the mosque and the graveyard with another wall other than the wall of the mosque or with a path that separates between them. This is better in order to be on the safe side so that the praying people would be far from facing the graves. However, if the graveyard is on the right or the left side of the mosque, or at the right or left side of the praying people, then this does not harm them as they are not facing it. Rather, in this case, they are not facing it and they are far from the doubt of facing it." [Ibn Baaz's Fataawa]
However, if there are graves inside the mosque, then it is not permissible to perform the prayer in it even if a wall is built between the mosque and the graveyard as we clarified in Fataawa 9943, 82773 and 127391.
Allaah Knows best.