make a subdomain with netlify dns in javascript

To create a subdomain with Netlify DNS in JavaScript, you need to follow these steps:

  1. Log in to your Netlify account and select the site you want to create the subdomain for.

  2. Click on the "Domains" tab in the left-hand menu.

  3. Click the "Add custom domain" button.

  4. Enter the subdomain you want to add in the first field (e.g. "subdomain"), and then select the domain from the drop-down menu (e.g. "example.com").

  5. Leave the "SSL/TLS certificate" section set to "Managed by Netlify".

  6. Click the "Verify" button to verify the domain.

  7. Next, you need to add a CNAME record to your domain's DNS settings. This tells the domain where to find the site hosted on Netlify. You can use the following JavaScript code to do this:

index.tsx
const netlifyAPI = require('netlify');

const client = new netlifyAPI(process.env.API_AUTH);

client.createDNSZone({
  body: {
    name: 'example.com',
  },
}).then(zone => {
  client.createDNSRecord({
    zone_id: zone.id,
    body: {
      type: 'CNAME',
      hostname: 'subdomain',
      value: 'example.netlify.app',
      ttl: 3600,
    },
  }).then(() => {
    console.log('CNAME record added');
  }).catch(err => {
    console.log(err);
  });
}).catch(err => {
  console.log(err);
});
493 chars
26 lines

This code uses the netlify NPM package to add a DNS zone and record for your subdomain. Make sure you have installed the netlify package and configured your API authentication details.

Replace process.env.API_AUTH with your Netlify API authentication token, and update the name, hostname, and value fields to match your domain and subdomain.

  1. Once you have added the CNAME record, wait for it to propagate (this can take up to 24 hours), and your subdomain should be accessible at subdomain.example.com.

gistlibby LogSnag