The Messenger of Allah ﷺ, the truthful and trusted, told us, "Each one of you has his creation gathered in his mother's womb for forty days. Then he becomes a clinging clot for the same period, then a lump of flesh for the same period. Then Allah sends an angel who is commanded with four words. He is told, 'Write down his deeds, his provision, his lifespan, and whether he will be wretched or happy.' Then the soul is breathed into him.A man among you may perform the deeds of the people of Paradise until there is only an arm's length between him and it, then what is written overtakes him and he performs the deeds of the people of the Fire and enters it. And a man may perform the deeds of the people of the Fire until there is only an arm's length between him and it, then what is written overtakes him and he performs the deeds of the people of Paradise and enters it."
حدثنا رسول الله ﷺ وهو الصادق المصدوق قال: إن أحدكم يجمع خلقه في بطن أمه أربعين يوما، ثم يكون علقة مثل ذلك، ثم يكون مضغة مثل ذلك، ثم يبعث الله ملكا فيؤمر بأربع كلمات، ويقال له: اكتب عمله، ورزقه، وأجله، وشقي، أو سعيد، ثم ينفخ فيه الروح، فإن الرجل منكم ليعمل حتى ما يكون بينه وبين الجنة إلا ذراع فيسبق عليه كتابه، فيعمل بعمل أهل النار، ويعمل حتى ما يكون بينه وبين النار إلا ذراع فيسبق عليه الكتاب فيعمل بعمل أهل الجنة.
Bukhari narrated it in the chapter on qadr (6594), and Muslim in the Book of Qadr (2643), both from the hadith of Amash, from Zayd bin Wahb, who said, Abdullah said, and he mentioned it. The wording given is that of Bukhari, and Muslim's wording is similar.