Doujinshi (同人誌), also romanized as dōjinshi, is the Japanese term for self-published print works, such as magazines, manga, and novels. Part of a wider category of doujin (self-published) works, doujinshi are often derivative of existing works and created by amateurs, though some professional artists participate in order to publish material outside the regular industry. -wikipedia
Doujinshi is any self published work, there are two type of doujinshi.
Niji sousaku, a doujinshi that uses existing characters
Ichiji sousaku, orginal artworks
Niji sousaku is just more popular so a lot of people think that it is the only definition of doujinshi. Also they're excepted by copyright issues, as long as it doesn't have any spoiler regarding the original manga, so people can create just as many fanmade mangas and sell them to the public. Sometimes authors do it themselves.
I have a question. So to my knowledge doujinshi (dj) is like a manga that uses characters from another existing manga, video game, anime,tv show, etc. I personally try not to read djs since they don’t interest me but I see lots of smut tagged as doujinshi when I’m certain it’s not from any existing source(usually is hentai). Why are they tagged with that? I swear I used to know this but forgot.