Fanfiction lives in this weird gray area where legality isn't always black and white. From my years of reading and occasionally writing fanfics, I've seen how it largely depends on how you handle copyrighted material. Most authors and studios tolerate non-commercial fanworks because they understand it comes from a place of love—it's free marketing that keeps fandoms alive! I mean, just look at how 'Harry Potter' fanfiction spawned entire subcultures without J.K. Rowling suing fans (though she did crack down on commercial ventures like 'Harry Potter and the Methods of Rationality'). The key is transformative use: if you're adding new perspectives, characters, or plots rather than just copying, you're safer.
That said, I once stumbled upon a 'Star Wars' fanfic that straight-up lifted whole chapters from Timothy Zahn's novels—that's a lawsuit waiting to happen. Platforms like AO3 protect writers through fair use arguments, but I always advise friends to avoid monetizing their work or using trademarks (you can't sell 'Marvel'-branded merch, even if your story is original). Some creators, like Anne Rice, famously hated fanfiction, while others like Neil Gaiman actively encourage it. It's less about 'is it legal?' and more 'will the copyright holder care?'—which makes every fandom's norms different.