SEXY Sofia Vergara has a BIG surprise up her sleeve – but it almost turned into a heartbreaking tragedy!

In a world exclusive scoop, The ENQUIRER can reveal that the 40-year-old “Modern Family” star is be­coming a mom the modern way – using a close friend as a surro­gate to carry her baby!

But the beauty’s secret plan to start a fam­ily with fiancé Nick Loeb nearly blew up when the surrogate was rushed to the hospital suffering ter­rifying symptoms of a miscarriage.

“After several hours, it was de­termined that the baby was fine, and so was the surrogate mom,” said a source close to the couple. “Sofia thanked God that everything was OK.”

The Latina bombshell – WHO already has a 20-year-old son – was pushed by Nick for months to have a child with her, and the source says that “after much soul searching,” she finally relented.

As The ENQUIRER disclosed in December, the couple repeatedly vis­ited reproductive specialists at UCLA Medical Center.

But sources say Nick didn’t want Sofia to lose her gorgeous shape or have to take a break from her lucra­tive work as a pitchwoman for several products in both the Latin and Amer­ican markets. So after much thought and consultation, she decided to find a surrogate.

“Rather than going through the trying process of hiring a stranger to serve as a surrogate, Sofia hand-picked one of her healthiest and closest friends,” the source told The ENQUIRER.

But something unexpected hap­pened just two nights before the Feb. 24 Academy Awards, and it threat­ened to turn the couple’s joy into a nightmare.

“Sofia’s surrogate had developed pain and went to the hospital, fearing that she was going to have a miscarriage,” said the source.

Sofia and Nick dashed from dinner at the BOA Steakhouse in West Hollywood and headed to the hospital in a panic.

Fortunately, it was a false alarm. But Sofia was spotted at the hospital, and to cover up her baby secret, sources say she put out word on her Instagram page that she had the flu.

Ironically, on “Modern Fam­ily,” Sofia’s character Gloria just had a baby, and she wore a pros­thetic belly to appear pregnant. Now she’s having a baby in real life – but without the belly! And her fiancé is said to be even more nervous about it than she is.

“Nick has been on edge through­out the whole process,” revealed the source. He’s hot-headed and becom­ing a dad is testing him. But Sofia would not have gone through all this if she wasn’t sure of her love and desire to marry Nick.

“Now, the only question is whether her wedding will come first – OR the baby.”