Fanfiction is a derivative work of copyrighted material and often trademarked characters, It is illegal according to USA copyright law. Derivative works, without the copyright holder’s permission, are illegal. However, the Internet has changed all that. Copyright holders and trademark holders are required to protect their copyrighted/trademarked material from being used illegally, but since the advent of the Internet that is impossible. Thus, in most cases, copyright and trademark infringement have been ignored with a whole lot less policing. That doesn’t mean it’s not illegal and you still can face lawsuit if a holder wants to stop you.
Amazon recently had whole bunch of favorite teen series out in fanfic editions, but they got permission from the copyright owners to do it and paid them royalties. That is the only legal way to do it. The same applies to YouTube for videos. You need to get licencing for covering a song through one of two agencies that handle it. If you put one up without the licencing it can be taken down if reported. That’s why so many cool videos are not there a few months down the road - they didn’t get permission and pay the fee. If you have too many of these incidents, YouTube will delete your account.
Fanfiction on sites like Wattpad, although technically illegal, are tolerated simply because it’d be impossible to go after the thousands of people writing them. Also, copyright holders have learned that they are good promotion for the original work. But it didn’t used to be before the Internet when such works usually appeared in fanzines. Then, many writers were warned by copyright owners’ lawyers to ‘cease and desist’. It was much easier to go after the much lesser number of fanzines than the great number of Internet sites.
Recently there were some fanfic Nancy Drew and similar characters books, self-pubbed, offered for sale on eBay. Simon and Schuster, who now own the characters, had them removed and the sellers warned not to sell them. The worst you can do is self-pub a fanfic book and try to sell it. But even then, nowadays, it starts out with warnings to ‘cease and desist’ rather than lawsuits.
As they often say, the Internet is changing everything.