It's quite easy, wandering round the small town of Billund, to start believing in the existence of a Lego god. You can't help but feel a master intelligence is at work here - the place is so manifestly wholesome, the street plan so well ordered, the pavements so tidy. Unostentatious automobiles proceed slowly along all-but-empty roads, stopping politely for pedestrians nowhere near a zebra crossing. A jovial red-and-yellow Lego giant points towards the town centre; huge coloured bricks lie scattered as if awaiting deployment in some exemplary new civic amenity (except that, being Denmark, it's not immediately apparent what else the town might need).

I half-expect to be plucked from the pavement, brushed up a bit and plumped down in front of the smart rectangular building labelled Head Office: Lego A/S. My goal here is to find out how, in the teeth of global recession and barely five years since it was being read the last rites, one of the world's best-loved brands has come back from the dead. For Lego, born of an earlier and tougher depression, is positively revelling in this one: the little studded, primary-coloured bricks are selling like never before. In Britain alone, the company's turnover last year was up 51%.

Its home town, though, is a bit too much for some people. "I couldn't ever live here," admits Mads Nipper, who looks and - when it comes to plastic bricks - acts about 12, but turns out to be one of the company's executive vice-presidents. "I'm nuts about Lego, believe me; I eat, sleep and breathe the stuff. But there's a bit too much of it around here even for me."

I got my first Lego set at the age of five. Bits of it are still in a chest at my parents' house: a grey plastic base board, an assortment of rectangular red-and-white bricks, a few square ones, roof tiles, beams, a little door that opens and shuts, a red-framed window with three transparent panes, red wheels with grey rubber tyres. Exactly the same set is on display in the Lego Idea House in Billund, the front of the box adorned with a carefree 1960s kid in a home-knitted sweater who could almost, bar the unnaturally blond curls, have been me. Just along from that set, though, is a selection of Bionicles, fierce warrior-robots with strange Polynesian names who live on the mythical-mystical isle of Mata Nui and fight each other with an array of unwholesome-looking weapons. My boy, now eight, liked those a lot a while ago. Now he is more into the Lego Star Wars Magnaguard Starfighter, whose 431-piece complexities he (and I) spent many hours wrestling with over Christmas. That is on display in Billund, too.

Charlotte Simonsen, the company's spokeswoman, says more than 400 million people will play with Lego this year. After 50-odd years of production, there are apparently 62 Lego bricks for every man, woman and child on the planet. And most of us, I'd imagine, would say we felt pretty warmly towards these little chunks of injection-moulded acrylonitrile butadiene styrene. Some would go considerably further. Lego reckons it has maybe 250,000 Afols, or Adult Fans of Lego, around the globe. They gather for mammoth week-long conventions with names such as BrickFest, and vie with each other to build the World's Largest Lego Boat (14ft 7in long; 300,000 bricks), construct the Biggest Lego Train Layout Ever (3,343ft, and it ran through an entire Lego cityscape) or beat the Fastest Time to Build the Lego Imperial Star Destroyer (3,104 pieces; five builders maximum and no pre-sorting allowed; record: 1 hour 42 minutes 43 seconds).

There are enthusiasts out there who make animated film shorts using characters and sets built solely of Lego. A man called Brendan Powell Smith has built The Brick Testament - 2,000 scenes from the bible - using Lego. And half a dozen people are Lego Certified Professionals: company-accredited creative artists whose working medium is Lego. I'm not sure how many of them, mind you, awakened by some nocturnal commotion, have rushed bleary-eyed into their children's bedroom at dead of night and stepped on a Lego brick in their bare feet. Had they done so, they would surely have cursed Lego and all its works, and wished Ole Kirk Christiansen had never been born back in 1891.

Christiansen was the inventor of Lego; his descendants still own the company today. He was a journeyman carpenter, son of a farm labourer, one child among 13. Kirsten Stadelhofer, a Lego employee for more than 30 years ("Plenty of people here," she says, "do 40.") tells me Ole Kirk's story. In 1916, he bought a small workshop, the Billund Maskinsnedkeri. In it he produced furniture, tools, stepladders, ironing boards, footstools, and, sometime in 1932, in the middle of the Great Depression, toys. To cheer the children up, he said.

Christiansen was by all accounts a good man, bespectacled, balding, universally liked. In 1934 he decided his growing company needed a rather catchier name than Billund Maskinsnedkeri and alighted on Lego, a contraction of the Danish leg godt, or play well. (It can also be construed to mean "I put together" in Latin.) At that stage he and his half-dozen employees turned out brightly coloured wooden cars, fire engines, pullalong chickens and quacking ducks. Christiansen was smart: when a 1930s yo-yo craze died, he sawed his stock in half. Each yo-yo made two wheels for a toy truck.

Quality was the watchword. Det beste er ikke for godt was his motto, or (roughly), Not even the best is good enough. Once, when his son Godtfred, who had worked in the factory since he was 12 and would eventually take it over, boasted that he had saved money by applying only two coats of varnish to a batch of toy ducks rather than the usual three, Christiansen made him go back and rectify his error, through the night, on his own.

"Lots of people," says Stadelhofer sternly, "might say that since it is only for children, it doesn't have to be well made. Ole Kirk thought that since it was for children, it could never be good enough."

In 1947, Lego bought Denmark's first injection-moulding machine and began making toys with some plastic components; its first big 100% plastic hit was a model Ferguson tractor, produced for Christmas 1951. Then, in 1949, Christiansen came across some intriguing English-made plastic building blocks called Kiddicraft, designed by a Hilary Harry Fisher Page, with little round studs on the top. Inspired, Lego started producing its own Automatic Binding Bricks.

The Lego System of Play - how virtuous it sounds now - was launched, to widespread indifference, in 1955. It consisted of 28 building sets, eight vehicles, various supplementary components, all interchangeable (as they still are; Lego bricks from the 1950s connect with their 2009 counterparts). The problem was, none of it really stuck together: the bricks were hollow.

After much painful experimentation, Godtfred, by now vice-president, patented the studs-and-tubes mechanism that made the system stable in January 1958. A toy that grasps simply, brilliantly even, what millions of children (and their parents) want, that today sells seven sets a second and has twice been named Toy of the Century, was born.

It would be nice to say Lego hasn't looked back since, but it wouldn't be true. At first, it did seem as if the company could do no wrong. In 1962, it expanded fast and furiously into Sweden, Belgium, France, Britain, America. The first Legoland, in Billund, opened in 1968, drawing an unprecedented 625,000 visitors in its inaugural summer to somewhere even the locals concede is quite a long way from anywhere.

To Lego City (the original town plan with its streets, houses, fire and police stations, unchanged in essence since 1955) were added Lego sets themed around space, robots, vikings, castles, space, the wild west and pirates - the first even remotely unfriendly looking Lego mini-figures, unshaven and scowling and carrying (heavens!) weapons. Then in the 1990s came the licensed products: Star Wars, Harry Potter, Bob the Builder, SpongeBob SquarePants, Indiana Jones. And then things started to go awry.

"We'd lost sight of what we were good at," says Simonsen. "There were other reasons too: the market was changing fast, children were getting older younger, computer games were really taking off. But basically, we'd got into movies, clothes, software games, own-brand stores, theme parks from Windsor to California - all non-core stuff that was absorbing vital management capacity. We'd moved far, far away from what we did well."

Suddenly, unthinkably, Lego was losing money. And not in a small way: after several years of increasingly heavy losses, in January 2004 the company reported a record deficit of Dkr1.4bn (£144m). Crippling debts amounted to more than Dkr5bn. There was fevered speculation that the Christiansen family (now, confusingly, spelled Kristiansen) would be forced to flog it, or large parts of it, to some all-American, plastic-fantastic interloper such as Mattel. All Denmark mourned.

Instead, Kjeld Kirk Kristiansen, Ole Kirk's grandson, took a deep breath and appointed a 36-year-old former McKinsey's management consultant called Jorgen Vig Knudstorp to dismantle Lego's sprawling house brick by brick, then put it back together again. Assets, including the Legoland theme parks, were sold. Whole product lines (particularly those for girls, with whom Lego has always had trouble engaging) were axed. More than 1,000 of the company's 3,500 jobs in Billund went, a shocking experience for a town whose pristine, ultra-automated factories produce some 36,000 Lego elements every minute - but one that seems, astonishingly, to have been accepted.

"This town isn't just about Lego any more, you know," observes a woman who asked to be called just Birgita, perching her youngest son on the back of her bicycle outside the supermarket. "It hasn't been for a long time. We're proud of Lego, certainly, but there are lots of other companies, lots of other jobs here now. The good thing was that all that happened when the rest of the economy was still in quite good shape. Heaven knows what it would have been like today, with half the world collapsing."

In two days in Billund I didn't meet anyone who felt Lego had behaved badly during the bad times. People were were looked after, retrained, and found other jobs. "In fact now we're doing well again, lots have come back," says Stadelhofer. "It's sounds like a cliche but really, Lego is a family."

It does feel a bit like that. The factories and packing centres may be operated largely by robots and automatic cranes, shuttling noiselessly between moulding machine, warehouse and sorting station with trays of green cacti, grey pirate swords and translucent spaceship windshields, but elsewhere gangs of cheerful Danish women pack boxes, engineers in white coats check tolerances - accurate, they say, to within 0.0002 of a millimetre - and the canteen at lunchtime is a warm uproar. The creative labs, though, are strictly off-limits.

Five years after reporting its heaviest ever loss, Lego last month said its net profit for 2008 had soared 32% to DKr1.35bn, on sales up a healthy 18.7%. Part of this recession-busting feat, Nipper concedes, is down to the fact that in times of trouble, consumers - in this case, parents - turn to "the well-known, the safe, the durable. Lego may not be the cheapest toy, but parents know it has stood the test of time, it will last years, provide hours of quality play, represent good value for their hard-earned money".

But also, he insists, Lego is cool again for kids. "Kids are ruthless little bastards," he says, only half in jest. "If they don't like the product, then at the end of the day the best marketing and distribution and all the rest of it won't make any difference. All you'll be doing is controlling the damage. What counts, all that counts, is that you're at the top of kids' wishlists. Which is, now, where we are again."

How to stay there, though, amid the combined onslaught of PlayStation and Xbox and Nintendo? It won't be easy. Nipper says Lego is confident children will continue to play with physical toys, although the company is active in the world of virtual play: an independent partner develops and markets successful console games based on Lego's Star Wars and Indiana Jones ranges, and Lego itself will be launching a children's MMOG - massively multiplayer online game - called Lego Universe next year.

Its ultimate goal, though, is somehow to integrate physical and virtual play. It is part of the way there: the website factory.lego.com allows you to download simple 3D design software, create a Lego toy online, then order the parts to build it; and there's a pretty funky robot, Mindstorms, for older children and adults, which communicates wirelessly with your computer and can be programmed to climb stairs, say, or select only the green M&Ms from a pile.

But Nipper dreams of a "seamless melding" of two interrelated worlds: a day when playing with a physical toy in a bedroom will somehow change its characteristics in an online multiplayer game, for example. Or vice versa. "Imagine," he says, "if kids were telling their playmates: 'Hey! Guess what! If you clip a set of shoulder pads on to this guy, he gets three times as many strength points online!' That would be the holy grail. But we're not there yet."

In the meantime, Lego is looking to a completely new venture. A British designer, Cephas Howard (who previously worked at the Guardian) has overseen the development of a series of 10 games, made mostly of existing Lego bricks and other components. First, you have to build them. Then, once you've played them, you can tinker with the board (by rebuilding it differently) or the dice, and see how the game changes. They won't be out until August, and much surrounding them is still secret. But the one I played with Howard in an office in Billund was an absolute cracker, based on the Ludo "get to the middle" principle, but with some very neat additions.

"When I was a kid," Howard says, "I had two passions: Lego and boardgames. Lego was great for imagination and creativity, but it was a solitary occupation. Boardgames were great for socialising, but they're not very creative. It seemed to me that if you combine the two, you might be on to something."

Howard's games haven't been launched yet, but already they're hoovering up innovation prizes at leading toy fairs. That Lego god, I'd say, is smiling.