On a recent summer day, Austin Knudsen, Montana’s attorney general, drove his red Buick from Helena, the state’s capital, to Boulder, a tiny town about a half-hour away whose main claim to fame is that it’s home to the state’s highway border patrol. The road was quiet, flanked by the sort of sprawling pastures and expansive landscapes that give Montana its nickname of Big Sky Country.

When Mr. Knudsen visits the highway patrol, which is under his purview, he swears by the steak and burgers at the Windsor, a local haunt that grills its meats behind the bar and where patrons can be spotted drinking beer straight from a pitcher.

As his meal arrived and the jukebox played music from the country artist and rodeo champion Chris LeDoux, Mr. Knudsen addressed the question that seemed particularly relevant given his current location: Why had he, the top cop in one of the country’s most sparsely populated states, put himself and Montana at the center of a fight between geopolitical superpowers?

In May, the state passed a law to ban TikTok that was drafted by Mr. Knudsen’s office. The law, which is the first of its kind in the United States, is set to go into effect in January, putting the state far ahead of Washington, D.C., where officials of both parties have been threatening — but not acting — to restrict use of the app. Federal lawmakers, just like Mr. Knudsen, have been concerned that TikTok could expose private user data to Beijing because the app is owned by ByteDance, a Chinese company.

The ban has led to a flurry of legal filings in recent weeks, with the first of many court showdowns expected in a few weeks.

Mr. Knudsen, between bites of a burger with American cheese and waffle fries, said the answer was simple.

“Congress has had hearings; they’re not doing anything,” the attorney general, 42, said. “Montanans don’t like being spied on, they don’t like their personal data being collected without their say so, and that to me is the crux of this.”

That easy answer, however, belies the complexity of the situation. Mr. Knudsen and Montana now face a legal brouhaha against some of the world’s biggest and most powerful tech companies as well as free speech groups. Locals, too, have questioned the wisdom of the ban and the state’s decision to take on this battle.

TikTok, one of the most popular apps in the United States, has said that the company does not pose a national security threat, and that its data collection practices are in line with the rest of the industry. Both the company and a group of creators in Montana that TikTok assembled have also argued that the ban violates their First Amendment rights, and that it intrudes on the federal government’s authority over foreign affairs and national security.

Opposition to the ban mounted last month in legal filings from the likes of the American Civil Liberties Union and the Computer & Communications Industry Association, whose members include Apple and Google. While residents will not be penalized for using the app under the new law, TikTok could face fines if they do use it — as could Apple and Google, if TikTok is available on their app stores in the state.

“The Montana law is unconstitutional,” Alex Haurek, a spokesman for TikTok, said. “We believe our legal challenge will prevail, and we look forward to our day in court.”

Mr. Knudsen said he was prepared for more than just one day in court. In his view, the ban is the culmination of nearly two years of he and his team scrutinizing the app, not some knee-jerk move. And he expects to defend it for years, even anticipating that it will make its way to the U.S. Supreme Court.

“I’m under no illusion that this is going to be quick — that would have been incredibly naïve,” Mr. Knudsen said.

Mr. Knudsen is a fifth-generation Montanan and a father of two teenagers and a 12-year-old — none of whom are allowed to use TikTok — who grew up on a farm and cattle ranch outside Culbertson, a town of fewer than 800 people in the northeast corner of the state. On his trip to Boulder he wore a blazer and cowboy boots, though not the cowboy hat he dons in some of his official portraits.

And let’s get this out of the way: He is not a fan of the hit TV show “Yellowstone,” in which the state’s attorney general is an easy-to-hate character.

A lawyer educated at Montana schools, his political profile grew over the past decade, turning him into one of the state’s most prominent Republicans. He spent two terms as speaker of the State House, and was elected as the attorney general in 2020.

While most of his attention has been focused on state issues, such as taxes and drug use, he describes himself as a longtime China hawk. By early 2022, after hearing from some residents that TikTok collected more user data than other similar services, he started to become a thorn in the company’s side.

Mr. Knudsen first asked the state’s information technology department to study TikTok’s data collection. He said the department raised red flags about the permissions TikTok sought in its terms with users, including its access to biometric information. That prompted an investigation into whether TikTok’s data collection practices violated state law. Mr. Knudsen demanded that ByteDance produce documents and respond to 80 questions about the app, including several about its addictive algorithm and its treatment of users under age 18.

In Mr. Knudsen’s telling, TikTok and ByteDance shared little in response, and what they did send was “very cursory, very high-end, very dismissive.”

Mr. Haurek, the TikTok spokesman, disputed Mr. Knudsen’s representation of the company’s response. He said that the company “produced documents, met with his office and provided briefings on multiple occasions.”

But Mr. Knudsen’s mind was made up and he began to think: Well, what can we do about this?

His answer was drafting the bill that would ban the app.

His effort soon got a boost, when the Pentagon said it had detected a Chinese spy balloon over Montana in February. For many state legislators, the balloon gave new weight to the concerns Mr. Knudsen had been raising about TikTok. According to the attorney general, the thinking went: If Beijing officials were willing to send a balloon to spy on the state, whether to monitor Montana’s military and nuclear installations and Air Force base or for some other purpose, what would stop them from looking into TikTok U.S. users’ photos and videos for the same purpose?

“It did really crystallize a lot of the public sentiment about privacy issues, about the extent of China’s spying apparatus,” Mr. Knudsen said.

TikTok has argued that connection is absurd. “We have not received any such request and we would not comply if we did,” Mr. Haurek said. But by April, the bill had passed the Republican-controlled state legislature. The governor, Greg Gianforte, also a Republican, signed it into law a month later.

The worries about China have not found widespread support among TikTok fans or small business owners in Montana, especially in Helena, a liberal enclave. Its quaint main street, called Last Chance Gulch, was sleepy on a recent afternoon, with several shops closed on Mondays. Tourists ambled past bronze statues of miners, and picnic blankets dotted the hill behind the Lewis & Clark Library ahead of a performance of Shakespeare in the Park.

Headwaters Crafthouse, a local taproom, promoted its opening in early 2021 on TikTok. Its owners, a married couple named Michael and Joan More, said that they viewed the ban as a distraction from more pressing local issues.

“It’s a headline-grabbing and attention-seeking move,” said Mr. More, 42, a fourth-generation Montanan. “Who’s going to win? Lawyers, and lawyers cost money and TikTok can spend millions of dollars on lawyers.” He added: “Stop wasting our tax dollars. Focus on things that actually need to get done.”

Brianne Harrington, owner of a pottery decorating studio, the Painted Pot, laughed when asked about the ban. “Our legislators this year were creating solutions for problems that didn’t exist,” she said.

Business owners and craftspeople who make money from TikTok have come out to defend the app, including on local billboards, but even businesses that don’t use TikTok were wary of a ban. Savanna Barrett, a co-owner of Lasso the Moon Toys, said that the store wanted young people to play with toys rather than smartphones, and that they usually advertised on Facebook and Instagram to reach parents and grandparents. But she opposed the restrictions on principle.

“Our current administration has no right to limit the self-expression of Montanans,” she said. “First Amendment rights apply to all American citizens, regardless of what country owns the platform they are using to express themselves.”

Under the new law, if a resident downloaded or used TikTok, the company and app stores could face daily fines of $10,000 per violation.

But there is plenty of legal wrangling to contend with before that happens.

TikTok has requested an injunction to block enforcement of the ban; a federal judge is scheduled to hold a hearing on that on Oct. 12.

In 2020, federal judges blocked then-President Donald J. Trump’s attempt to ban TikTok, saying that the administration likely overstepped its authority by invoking emergency economic powers to bar the app. Several legal experts have predicted that Montana’s ban will struggle against arguments that it infringes on users’ First Amendment rights and that it, too, has overstepped its authority by wading into an arena that should be under the purview of the federal government.

“It’s hard for me to believe that courts would abide such a broad ban,” said Anupam Chander, a visiting scholar at the Institute for Rebooting Social Media at Harvard.

Mr. Knudsen argued in a recent filing that the law was “narrowly tailored” and that it left other channels of internet expression “untouched.” Mr. Knudsen also said the case, in the course of discovery, would force TikTok to make new disclosures about how China figures into its work force, perhaps changing some opinions. “That’s when we’ll actually start getting some meat and potatoes documentation about structure, who’s in control of what.”

He said the ban could even interest the Supreme Court, which could perhaps use the case to address some questions about how social media platforms should be regulated.

As he finished his waffle fries at the Windsor, the two older men at the bar and the bartender did not seem to be paying any attention to his discussion of international relations and modern-day technology. Their minds seemed elsewhere.

And that was fine with Mr. Knudsen.

“It’s kind of fun,” he said, “being on the cutting edge of a few of these things.”