Security services should only retain data from telephone calls and emails if it is used to fight serious crime, the European Court of Justice has ruled.
The ECJ's advocate general, Henrik Saugmandsgaard Oe, said there was a "general obligation" that retaining data may be compatible with EU law.
His preliminary ruling is likely to be followed by the full ECJ court.
It comes after British courts ruled the Data Retention and Investigatory Powers Act (Dripa) was illegal.
This permits Britain's security agencies and some other public bodies to gather information about people whom suspects contact by telephone or email.
Dripa was rushed through Parliament in July 2014, after a ruling by the ECJ rendered existing powers illegal.
The government appealed against the British courts' ruling and the case was referred to the ECJ, which is the highest court in the European Union.
Mr Saugmandsgaard Oe has now made the ruling to clarify EU law, saying that a "general obligation to retain data may be compatible with EU law" but this is "subject to satisfying strict requirements".
These include respecting the "essence of the right to respect for private life and the right to the protection of personal data laid down by the Charter [the EU Charter of Fundamental Rights]".
He added: "The fight against serious crime is an objective in the general interest that is capable of justifying a general obligation to retain data."
But he said this obligation must be "strictly necessary to the fight against serious crime," and "proportionate".
Conservative MP David Davis - now the Brexit secretary - and Labour's deputy leader Tom Watson successfully argued in British courts a year ago against the Dripa act.
Two High Court judges found that the act was "inconsistent with EU law".
Mr Watson said that this legal opinion shows Prime Minister Theresa May, who was formerly the home secretary, "was wrong to pass legislation... that allows the state to access huge amounts of personal data without evidence of criminality or wrongdoing.
"Labour has already secured important concessions but I hope the government she leads will now revisit it.
"The opinion makes it clear that information including browsing history and phone data should not be made available to the security services and other state bodies without independent authorisation."
Mr Watson also said that while the security services "have an important job to do", judicial oversight is required "if we are to maintain the right balance between civil liberties and state power".
Meanwhile, a hearing of the Investigatory Powers Tribunal, which handles complaints against UK intelligence agencies MI5, MI6 and GCHQ, is due to be held this month.
Campaign group Privacy International is challenging the agencies' use and acquisition of "bulk personal datasets" - very large amounts of personal data collected from public and private organisations.