BRUSSELS—U.K. Prime Minister Boris Johnson’s government and the European Union agreed to new terms for the country’s exit from the bloc Thursday, paving the way for a high-stakes vote in the British Parliament.

The accord was endorsed by the leaders of the other 27 EU countries at a summit here. Mr. Johnson now faces the formidable challenge of winning backing for the deal from Parliament. In a setback for the deal’s prospects, a political party allied with his government said it wouldn’t support the deal.

Following days of intense talks more than three years after Britain voted to leave the EU, the two sides struck a compromise intended to ensure a border doesn’t appear on the island of Ireland. It was the main sticking point in negotiations aimed at smoothing Britain’s split with its largest trading partner.

The breakthrough marks an unexpected turn of events in Britain’s tortured journey out of the EU and a victory for Mr. Johnson, who has pledged to deliver on the result of the 2016 referendum. It comes after weeks of at times acrimonious confrontations between U.K. and EU officials over the terms of Brexit, scheduled for Oct. 31.

The proposed deal would leave Britain freer to set its own rules and strike trade deals independently from the EU, a key demand of Brexit supporters.