With the final third of votes to be counted, Obama said to his supporters he was "still fired up and ready to go," but conceded defeat to Clinton.
"I want to congratulate Senator Clinton on a hard-fought victory here in New Hampshire. She did an outstanding job."
Terry McAuliffe, Clinton's adviser and former democratic national committee chairman, said: "This is a big, big win for us. It's now a one-on-one race. It's Hillary Clinton versus Barack Obama. We've got 25 more states to go."
Clinton triumphed despite a flood of polls showing her with a double-digit deficit against Obama. The win gives her a big dose of momentum in a seesawing campaign.
McCain, meanwhile, capped his rise from the political scrap heap with a win over Mitt Romney, the former governor of Massachusetts who has poured tens of millions of dollars of his personal wealth into the race.
"I'm past the age when I can claim the noun 'kid' no matter what adjective precedes it. But tonight we sure showed them what a comeback looks like," he said to his supporters who repeatedly chanted, "Mac is back!"
The victory put McCain, an Arizona senator, in the middle of a scramble for the party's nomination for the November election after being written off this summer when he was low on cash and shedding campaign staff.
McCain won 37 per cent of the votes while Romney got 32 per cent.
John Edwards, Democratic presidential hopeful and former North Carolina senator, was far behind Clinton and Obama in third place.
Republican Mike Huckabee, the former Arkansas governor who won in Iowa last week, came in third with 12 per cent.
Polls closed around the state on Tuesday after a day of frantic last-minute campaigning and heavy voter turnout, signalling that many independents had showed up to vote.
Campaign and state officials reported large crowds at some polling stations, aided by the unseasonably balmy weather, with predictions of a record turnout.
New Hampshire's primary is the second high-profile battleground, following Iowa, in the state-by-state process of choosing Republican and Democratic candidates for November's election to succeed George Bush as president.
The election race now heads into an intense month of campaigning culminating in the Super Tuesday nominating contests on February 5, when some 22 states pick presidential candidates.