Yes. It is legal to work in many countries, even if you’re not a resident. But you will have to comply with the tax and immigration requirements to be able to stay there legally. Many countries now offer digital nomad visas to people who want to work in their country as non-residents.