The Prophet ﷺ said, "When you arrive and the imam is bowing, then bow. If he is prostrating, then prostrate. But do not count the prostration if it was not preceded by bowing with him."
عن النبي ﷺ قال: إذا جئتم والإمام راكع فاركعوا، وإن كان ساجدا فاسجدوا، ولا تعتدوا بالسجود إذا لم يكن معه الركوع.
No references are available.
Bayhaqi (2/89) narrated it from Abu Abdullah Hafiz, who said, Muhammad bin Ahmad bin Baluyah informed me, Muhammad bin Ghalib told us, Amr bin Marzuq told me, Shubah informed us, from Abdul-Aziz bin Rafi, from a man, from the Prophet ﷺ, and he mentioned it. This unnamed man is Abdullah bin Mughafal Muzani, the well known companion, as stated in the Masail of Ahmad and Ishaq.However, Sufyan narrated it from Abdul-Aziz bin Rafi, from an elder of the Ansar, who said, a man entered the masjid and heard the Messenger of Allah ﷺ the sound of his sandals. When he had finished the salutation, he said, "How did you find us?" The man said, "In prostration, so I prostrated." He said, "Do that, but do not count the sajdah unless you have caught the rakat. So when you see the imam standing, stand, and when he is bowing, bow, and when he is prostrating, prostrate, and when he is sitting, sit."Musaddad narrated it, as found in Matalib (479), and Abdul-Razzaq (3373), and Bayhaqi (2/296), all of them through routes from Sufyan Thawri, from Abdul-Aziz bin Rafi with his chain in similar wording, and the wording given here is Musaddad's.Ibn Hajar said, "Sahih." He means that the elder of the Ansar was a companion, for he was present at the incident, and by this the hadith is established as sahih.The way to reconcile the two versions is that Shubah confined himself to the raised wording and did not mention the story, while Sufyan Thawri mentioned the raised wording along with the story, so there is no contradiction between them.