I plan to drive a 51 ohm LED using the pi's 5v pin using a 2n2222 transistor connected to the GPIO. Do I need a resistor on the base pin of the transistor or can I connect it directly to a GPIO pin?
There are two answers to your question of "need":
Yes - you need a resistor between the base junction of the transistor and the GPIO pin. Otherwise, the current flowing into the base junction of the transistor will exceed the GPIO's "safe" limits. In other words you may damage your RPi - you'll certainly not be following best practices.
No - you can connect the GPIO directly to the base of your transistor. If you review a data sheet for the 2N2222, and you care to muddle through all the vagariessee below in the published GPIO specifications, it seems likely (to me) that you can drive the base of a 2N2222 transistor directly from a GPIO pin without destroying them immediately. But given that a resistor can be bought for a few cents, you should ask yourself if that's a risk you want to take.
In other words, this is the same situation you probably face every day with your car, your hob and all the other appliances you use. You have a choice: you can operate them within suggested limits, or you can push them to their limits.
Here are some references if you're interested in further reading:
The "Official GPIO Documentation" on the RPi GPIO is written for the BCM2835 - the Broadcom processor used in Raspberry Pi 1 and Zero; ca. 2011. The Foundation has not yet updated their "Official GPIO Documentation" for the RPi 2, 3 or 4. This may mean the BCM2835 GPIO documents remain valid - or it may not. The same can be said for the explicit "Gert van Loo documents" - which are far more enlightening, but also dated.
The CM4 documentation addresses the BCM2711 (the RPi 4B SoC), and covers some of the details in the "Official GPIO Documentation", but not all. You can follow this question if you're interested in the possible update and clarification of the GPIO electrical characteristics.
What does all of this mean? While the ultimate limits of the Raspberry Pi GPIO are not as clear as some of us would like, there does seem to be general agreement that a GPIO pin can safely source or sink 16 mA.
The short answer is YES. The longer answer is it depends.
In a common emitter configuration (the most common) you NEED to limit current. This needs to be sufficient to saturate the transistor. For a light load of 20 mA this is not critical. A value of 1kΩ would limit current to the nominal 3.3mA and drive loads of several hundred mA with most transistors.
In emitter follower configuration no resistor is needed and the emitter voltage would track base voltage. This has the disadvantage that excess voltage would be dissipated by the transistor as heat.
Incidentally there is no such thing as a 51 ohm LED.