We study the optimal design of a central bank digital currency (CBDC) in an environment where agents sort into cash, CBDC and bank deposits according to their preferences over anonymity and security; and where network effects make the convenience of payment instruments dependent on the number of their users. CBDC can be designed with attributes similar to cash or deposits, and can be interest-bearing: a CBDC that closely competes with deposits depresses bank credit and output, while a cash-like CBDC may lead to the disappearance of cash. Then, the optimal CBDC design trades off bank intermediation against the social value of maintaining diverse payment instruments. When network effects matter, an interest-bearing CBDC alleviates the central bank's tradeoff.