No, it is not illegal under U.S. federal law to write on the American flag. The United States Flag Code (4 U.S.C. §§ 5–10) establishes advisory customs for respectful display and handling—including a provision that the flag "should never have placed upon it, nor on any part of it, nor attached to it any mark, insignia, letter, word, figure, design, picture, or drawing of any nature"—but the Flag Code carries no criminal penalties and is not enforceable by law.
The Supreme Court has ruled twice (Texas v. Johnson, 1989; United States v. Eichman, 1990) that flag desecration (burning, defacing, etc.) is expressive conduct protected by the First Amendment. Congress cannot criminalize it without violating free speech. The Flag Code remains as a voluntary guide for civilians and a mandatory regulation for military and federal agencies (by executive order), but private citizens face no legal sanction for writing on, wearing, or otherwise modifying the flag.
While legal, writing on the flag is widely viewed as disrespectful by veterans' groups, patriotic organizations, and many citizens. It may provoke strong negative reactions, social ostracism, or professional consequences (e.g., for public figures, military personnel under UCMJ Article 134 for conduct unbecoming). The Flag Code reflects a consensus on how the flag ought to be treated to honor what it represents.
If a flag becomes soiled or damaged (including by writing), the Flag Code recommends dignified destruction, preferably by burning, often conducted ceremonially by groups like the American Legion, VFW, or Boy Scouts.
Bottom line: You can write on the flag without breaking the law, but you should not if you wish to observe the nation's shared standards of respect for its primary symbol.