The Spanish giants had announced in the summer that Messi, 30, had committed his future to the club but the Argentine had not signed the new deal.
With his previous contract set to expire in 2018, Messi could have left Barca for free next summer had he not extended his deal.
"FC Barcelona and Lionel Messi signed today morning a new contract that will keep the Argentinian superstar at the club through the 2020/21 season," read a club statement. "The buyout clause was set at 700 million euros ($835 million)."
Pressure has been mounting on beleaguered Barca president Josep Maria Bartomeu to get Messi to put pen to paper.
Also Read
Bartomeu was heavily criticised for his role in Neymar's departure and a haphazard search for replacements in the final weeks of the transfer window.
However, Bartomeu saw off a vote of no confidence measure launched by disgruntled fans thanks to Barca's fantastic start to the season, in large part inspired by Messi's form.
Messi's 30 trophies are along with teammate Andres Iniesta the most in Barca's history, including eight La Liga and four Champions League titles.
The diminutive Argentine, who joined Barca at the age of 13, has also smashed 523 goals in 602 games to become the Catalans' all-time top goalscorer.
News of Messi's renewal also comes as a huge boost to the La Liga leaders ahead of Sunday's top of the table clash at Valencia (1945GMT).
Barca lead a revitalised Valencia by four points, with both Real Madrid and Atletico Madrid a further six points adrift, thanks to a club record start of 11 wins and one draw from 12 games.
Disclaimer: No Business Standard Journalist was involved in creation of this content