It depends a bit on what you really want to do.
Technically, you can generate a certificate in a derivation, but that’s usually A Bad Idea™, as the results of a derivation - which would include the private key for the certificate - are world-readable.
You also have an issue with reproducability, the certificate could be regenerated pretty much at a random time… or never, even when you need to recreate it.
The common thing to do is to have a derivation that outputs a simple script that generates the certificate if it does not exist on the system.
Just call that script before you start whatever needs the certificate.
That’s basically what the SSH module for NixOS does. before starting sshd it checks if the key already exists. If not, it generates a new ssh key for the host.
The interesting part is around line 417: