There is no definitive answer to this question as it depends on a variety of factors, such as the country you reside in and the type of fanfiction you are writing. In some cases, writing fanfiction may be illegal if it infringes on copyright laws, while in other countries it is generally tolerated. It is always advisable to check with a legal professional if you are unsure about the legality of writing fanfiction.