Nginx ngx_http_sub_module module syntax is :
sub_filter string replacement;
In nginx strings may be inputted without quotes unless they include blank spaces, semicolons or curly braces. When those characters are present they need to be escaped with backslashes or the strings need to be enclosed in single/double quotes. (Variables in quoted strings are going to be expanded unless the $
is escaped.)
You can thus simply escape the spaces (and don't quote the string):
sub_filter </BODY> <script\ defer\ src="https://static.cloudflareinsights.com/beacon.min.js"\ data-cf-beacon='{"token":\ "aaabbbccc55dd"}'></script>\ </BODY>;
Escaping the quotes should be redundant but doing so shouldn't be harmful either:
sub_filter </BODY> <script\ defer\ src=\"https://static.cloudflareinsights.com/beacon.min.js\"\ data-cf-beacon='\{\"token\":\ \"aaabbbccc55dd\"}\'></script>\ </BODY>;
or, you can quote the strings with either single or double quotes and then escape those single or double quotes (with a \) whenever they occur in your strings:
sub_filter '</BODY>' '<script defer src=\'https://static.cloudflareinsights.com/beacon.min.js\' data-cf-beacon=\'{"token": "aaabbbccc55dd"}\'></script> </BODY>';
sub_filter "</BODY>" "<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{\"token\": \"aaabbbccc55dd\"}'></script> </BODY>";