Bulugh al-Maram 533
وَعَنْ أَنَسٍ - رضي الله عنه - قَالَ: قَالَ رَسُولُ اللَّهِ - صلى الله عليه وسلم: «لَا يَتَمَنَّيَنَّ أَحَدُكُمُ الْمَوْتَ لِضُرٍّ يَنْزِلُ بِهِ, فَإِنْ كَانَ لَا بُدَّ مُتَمَنِّيًا فَلْيَقُلْ: اللَّهُمَّ أَحْيِنِي مَا كَانَتِ الْحَيَاةُ خَيْرًا لِي, وَتَوَفَّنِي إِذَا كَانَتِ الْوَفَاةُ خَيْرًا لِي». مُتَّفَقٌ عَلَيْهِ.
Anas, may Allah be pleased with him, said: The Messenger of Allah ﷺ said: "None of you should wish for death because of some harm that befalls him. If he must wish, let him say: 'O Allah, keep me alive as long as life is better for me, and take me when death is better for me.'" Agreed upon.