The new rule comes from Iran's Supreme Council of Cyberspace and firms have been given one year to comply.
Campaign group Privacy International described it as "extremely worrying" but said it could prove difficult to enforce.
Iran's most popular messaging app is Berlin-based service Telegram, believed to be used by one in four Iranians.
Messages shared via Telegram, which is free to use, are encrypted and can be seen by many users at once.
Telegram could not be reached for comment but reports circulating on social networks that it has decided to comply are understood to be false.
Most social networks are officially blocked by the state but lots of people are able to access them via services like Virtual Private Networks (VPNs), which mask a browser's geographical location.
The country's president, Hassan Rouhani, has active Twitter accounts in English and Persian.
In my view, Telegram has a tough job ahead of it when deciding whether to go ahead with what the government wants.
People are worried about losing it but they are also saying they will stop using it if the firm complies with the new law.
This is a big thing for people in Iran. They are very sensitive about security.
If Telegram does what is asked, then the government will have control over the content, it can monitor who is saying what, and it can arrest people.
The app was shut down briefly last year for refusing to comply with the government - and that added to its popularity.
Just recently BBC Persian covered a story about high school students protesting about their exams - they created a Telegram group to mobilise and inform other students about the protest.
The group got 20,000 subscribers and the protest went well. But as soon as it got media coverage the government told the group administrators to close it down.
In a short time, the number of subscribers came down to just 300.
Instant messaging apps must store data about Iranian users inside the country, Iran has ordered.