Tag: Netlify

Netlify CMS Open Authoring

I like the term “Git-backed CMS.” That term works for an emerging style of CMS that looks and behaves much like any other CMS, with a fascinating twist: it doesn’t actually store any data for you. These CMSs are connected to a Git repo where the data lives in flat files (e.g. Markdown). You teach the CMS where those files are and how they are structured. Then, as you use the CMS to create, edit, and delete things, those changes happen has commits (or pull/merge requests) are made against that repo. So cool.

For example, CloudCannon can do it specifically for hosted Jekyll sites.

But more in the Indie Web / JAMstack spirit, there are players like Forestry and the one I have the most experience with: Netlify CMS.

Lemme do a series of screenshots with captions to make the point very clear.

The site in question is our Serverless site. It happens to be Gatsby, but the important part is that that the content comes from Markdown files in a Git repo.
Here’s an example Markdown file (with Frontmatter) in the repo. I like Markdown fine, but I’d prefer to work with content in a GUI CMS honestly. The reason I went this way is so the data is in a repo, meaning I can take content-based pull requests.
I really do get content-based pull requests. That’s the magic right there. That’s exactly what I want.
Netlify CMS is basically two files. An index.html that loads up a SPA interface that literally does everything. And a configuration file to teach it about your content.
With Netlify CMS in place, I have my GUI CMS happy place. Any changes in here turn up as commits on the repo.

OK OK OK. What’s this “Open Authoring” thing?

As I write, it’s a beta feature.

Here’s the main thing: I can use Netlify CMS for my site. My team can also use it, because I can invite them specifically to the repo. But you, random person on the internet, cannot. If you wrote to me and told me you wanted to be a volunteer content manager on the site, then maybe, OK, I’ll invite you to the repo. (You being a member of the repo will allow you to auth into Netlify CMS, assuming you are using the GitHub back end, which is the only connection Open Authoring works with right now.)

But that’s a bummer that random internet people can’t submit pull requests on content via Netlify CMS. That would be way easier than the manual process of forking the repo and all that jazz — although to be fair, click the little pencil icon while looking at a Markdown file on GitHub and editing it makes the process pretty simple by opening a pull request automatically (but it doesn’t help you add new content or upload images or anything).

This is where Open Authoring comes in. In my Netlify CMS config I can basically flip it on with one line of config. They explain it well:

you can use Netlify CMS to accept contributions from GitHub users without giving them access to your repository. When they make changes in the CMS, the CMS forks your repository for them behind the scenes, and all the changes are made to the fork. When the contributor is ready to submit their changes, they can set their draft as ready for review in the CMS. This triggers a pull request to your repository, which you can merge using the GitHub UI.

Emphasis mine.

Wanna see the real beauty of this? Now we can put “Edit this” buttons on all the content, and if you click it, you’ll head straight into Netlify CMS to do the editing. It works if you are me, my team member, or you, random person from the internet.

That’s what I’ve always wanted. It makes the site into a wiki! But there is enough public accountability (they have to use a real GitHub account) that I wouldn’t worry about much spam or obnoxious behavior.

The post Netlify CMS Open Authoring appeared first on CSS-Tricks.

CSS-Tricks

, ,

Netlify Build Plugins Announcement

Netlify just dropped a new thing: Build Plugins. (It’s in beta, so you have to request access for now.) Here’s my crack at explaining it, which is heavily informed from David Well’s announcement video.

You might think of Netlify as that service that makes it easy to sling up some static files from a repo and have a production site super fast. You aren’t wrong. But let’s step back and look at that. Netlify thinks about itself as a platform in three tiers:

  1. Netlify Build
  2. Netlify Dev
  3. Netlify Edge

Most of the stuff that Netlify does falls into those buckets. Connecting your Git repo and letting Netlify build and deploy the site? That’s Build. Using Netlify’s CLI to spin up the local dev environment and do stuff like test your local functions? That’s Dev. The beefed-up CDN that actually runs our production sites? That’s Edge. See the product page for that breakdown.

So even if you’re just slapping up some files that come out of a static site generator, you’re still likely taking advantage of all these layers. Build is taking care of the Git connection and possibly running a npm run build or something. You might run netlify dev locally to run your local dev server. And the live site is handled by Edge.

With this new Build Plugins release, Netlify is opening up access to how Build works. No longer is it just “connect to repo and run this command when the build runs.” There is actually a whole lifecycle of things that happen during a build. This is how David described that lifecycle:

  1. Build Starts
  2. Cache is fetched
  3. Dependencies are installed
  4. Build commands are run
  5. Serverless Functions are built
  6. Cache is saved
  7. Deployment
  8. Post processing

What if you could hook into those lifecycle events and run your own code alongside them? That’s the whole idea with Build Plugins. In fact, those lifecycle events are literally event hooks. Sarah Drasner listed them out with their official names in her intro blog post:

  • init: when the build starts
  • getCache: fetch the last build’s cache
  • install: when the project’s dependencies are installing
  • preBuild: runs directly before building the functions and running the build commands
  • functionsBuild: runs when the serverless functions are building, if they exist on the site
  • build: when the build commands are executing
  • package: package it to be deployed
  • preDeploy: runs before the built package is deployed
  • saveCache: save cached assets
  • finally: build finished, site deployed 🚀

To use these hooks and run your own code during the build, you write a plugin (in Node JavaScript) and chuck it in a plugins folder at like ./plugins/myPlugin/index.js

function netlifyPlugin(conf) {   return {     // Hook into lifecycle     finally: () => {       console.log("Finished!")     }   } }  module.exports = netlifyPlugin

…and adjust your Netlify config (file) to point to it. You’re best off reading Sarah’s post for the whole low-down and example.

OK. What’s the point?

This is the crucial part, right? Kind of the only thing that matters. Having control is great and all, but it only matters if it’s actually useful. So now that we can hook into parts of the build process on the platform itself, what can we make it do that makes our lives and sites better?

Here’s some ideas I’ve gathered so far.

Sitemaps

David demoed having the build process build a sitemap. Sitemaps are great (for SEO), but I definitely don’t need to be wasting time building them locally very often and they don’t really need to be in my repo. Let the platform do it and put the file live as “a build artifact.” You can do this for everything (e.g. my local build process needs to compile CSS and such, so I can actually work locally), but if production needs files that local doesn’t, it’s a good fit.

Notifications

Sarah demoed a plugin that hits a Twilio API to send a text message when a build completes. I do this same kind of thing having Buddy send a Slack message when this site’s deployment is done. You can imagine how team communication can be facilitated by programmatic messaging like this.

Performance monitoring

Build time is a great time to get performance metrics. Netlify says they are working on a plugin to track your Lighthouse score between deployments. Why not run your SpeedCurve CLI thing or Build Tracker CLI there to see if you’ve broken your performance budget?

Optimizations

Why not use the build time to run all your image optimizations? Image Optim has an API you could hit. SVGO works on the command line and Netlify says they are working on that plugin already. I’d think some of this you’d want to run in your local build process (e.g. drop image in folder, Gulp is watching, image gets optimized) but remember you can run netlify dev locally which will run your build steps locally, and you could also organize your Gulp such that the code that does image optimization can build part of a watch process or called explicitly during a build.

Images are a fantastic target for optimzation, but just about any resource can be optimized in some way!

Bailing out a problematic builds

If your build process fails, Netlify already won’t deploy it. Clearly useful. But now you could trigger that failure yourself. What if that performance monitoring didn’t just report on what is happening, but literally killed the build if a budget wasn’t met? All you have to do is throw an error or process.exit, I hear.

Even more baller, how about fail a build on an accessibility regression? Netlify is working on an Axe plugin for audits.

Clearly you could bail if your unit tests (e.g. Jest) fail, or your end-to-end tests (e.g. Cypress) fail, meaning you could watch for 404’s and all sorts of user-facing problems and prevent problematic deploys at all.

Use that build

Netlify is clearly all-in on this JAMstack concept. Some of it is pretty obvious. Chuck some static files on a killer CDN and the site has a wonderfully fast foundation. Some of it is less obvious. If you need server-powered code still, you still have it in the form of cloud functions, which are probably more powerful than most people realize. Some of it requires you to think about your site in a new way, like the fact that pre-building markup is not an all-or-nothing choice. You can build as much as you can, and leave client-side work to do things that are more practical for the client-side to do (e.g. personalized information). If you start thinking of your build process as this powerful and flexible tool to offload as much work as possible to, that’s a great place to start.

The post Netlify Build Plugins Announcement appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

My Favorite Netlify Features

👋 Hey folks! Silvestar pitched this post to us because he is genuinely enthusiastic about JAMstack and all of the opportunities it opens up for front-end development. We wanted to call that out because, although some of the points in here might come across as sponsored content and Netlify is indeed a CSS-Tricks sponsor, it’s completely independent of Netlify.

Being a JAMstack developer in 2019 makes me feel like I am living in a wonderland. All these modern frameworks, tools, and services make our lives as JAMstack developers quite enjoyable. In fact, Chris would say they give us superpowers.

Yet, there is one particular platform that stands out with its formidable products and features — Netlify. You’re probably pretty well familiar with Netlify if you read CSS-Tricks regularly. There’s a slew of articles on it. There are even two CSS-Tricks microsites that use it.

This article is more of a love letter to Netlify and all of the great things it does. I decided to sit down and list my most favorite things about it. So that’s what I’d like to share with you here. Hopefully, this gives you a good idea not only what Netlify is capable of doing, but helps you get the most out of it as well.

You can customize your site’s Netlify subdomain.

When creating a new project on Netlify, you start by either:

  • choosing a repository from a Git provider, or
  • uploading a folder.

The project should be ready in a matter of minutes, and you could start configuring it for your needs right away. Start by choosing the site name.

The site name determines the default URL for your site. Only alphanumeric characters and hyphens are allowed.

Netlify randomly creates a default name for a new project. If you don’t like the name, choose your own and make it one that would be much easier for you to remember.

The “Site information” section of the Netlify dashboard.

For example, my site name is silvestarcodes, and I could access my site by visiting silvestarcodes.netlify.com.

You can manage all your DNS on Netlify.

If you are setting up an actual site, you would want to add a custom domain. From the domain management panel, go to the custom domains section, click on the “Add custom domain” button, enter your domain, and click the “Verify” button.

Now you have two options:

  1. Point your DNS records to Netlify load balancer IP address
  2. Let Netlify handle your DNS records

For the first option, you could read the full instructions in the official documentation for custom domains.

For the second option, you should add or update the nameservers on your domain registrar. If you didn’t buy the domain already, you could register it right from the dashboard.

Netlify has a service for provisioning DNS records called Netlify DNS.

Once you have configured the custom domain, you could handle your DNS records from the Netlify dashboard.

The “DNS” section of the Netlify dashboard.

If you want to set up a dev subdomain for your dev branch to preview development changes for your site, you could do it automatically. From the Domain Management section in the Settings section of your site, select the dev branch and Netlify would add a new subdomain dev for you automagically. Now you could see the previews by visiting dev subdomain.

The “Subdomains” section of the Netlify dashboard.

You could configure a subdomain for a different website. To achieve this, create a new Netlify site, enter a new subdomain as a custom domain, and Netlify would automatically add the records for you.

As an icing on the DNS management cake, Netlify lets you create Let’s Encrypt certificates for your domain automatically… for free.

You can inject snippets into pages, which is sort of like a Tag Manager.

Snippet injection is another excellent feature. I am using it mostly for inserting analytics, but you could use it for adding meta tags for responsive behavior, favicon tags, or Webmention.io tags.

The “Snippet injection” section of the Netlify dashboard.

When inserting snippets, you could choose to append the code fragment at the end of the <head> block, or at the end of the <body> block.

Every deploy has its own URL forever.

Netlify creates a unique preview link for every successful build. That means you could easily compare revisions made to your site. For example, here is the link to my website from January this year, and here is the link from January last year. Notice the style and content changes.

In his talk, Phil Hawksworth calls this feature immutable, atomic deploys.

They are immutable deployments that live on forever.
— Phil Hawksworth

I found this feature useful when completing tasks and sending the preview links to the clients. If there is a person in charge of handling Git-related tasks, like publishing to production, these preview links could be convenient to understand what to expect during the merge. You could even set up the preview builds for every pull request.

Netlify allows for the cleanest and most responsible A/B testing you can do.

If you ever wanted to run A/B tests on your site, you would find that Netlify makes running A/B tests quite straightforward. Split testing on Netlify allows you to display different versions of your website from different Git branches without any hackery.

The “Split testing” section of the Netlify dashboard.

Start by adding and publishing a separate branch with desired changes. From “Split testing” panel, select which branches to test, set a split percentage, and start the test. You could even set a variable in analytics code to track which branch is currently displayed. You might need to active branch deploys if you didn’t do this already.

Netlify’s Split Testing lets you divide traffic to your site between different deploys, straight from our CDN network, without losing any download performance, and without installing any third party JavaScript library.
Netlify documentation

I have been using A/B testing on my site for a few different features so far:

  • Testing different versions of contact forms
  • Displaying different versions of banners
  • Tracking user behavior, like heatmaps

If you want to track split testing information, you could set up the process environment variable for this purpose. You could learn more about it in the official documentation. The best part? Most A/B testing services use client-side JavaScript to do it, which is unreliable and not great for performance. Doing it at the load balancer level like this is so much better.

There are lots of options for notifications, like email and Slack.

If you want to receive a notification when something happens with your Netlify project, you could choose from a wide variety of notification options. I prefer getting an email for every successful or failed build.

The “Notifications” section of the Netlify dashboard.

If you are using Gmail, you could notice “See the changes live” link for every successful build when hovering your message in Gmail inbox. That means you could open a preview link without opening the email. There are other links like “See full deploy logs” when your build have any issues or “Check usage details” when your plan is near its limits. How awesome is that?

Netlify email notifications include a preview link.

If you want to set up a hook for third-party services, all you need is a URL (JWS secret token is optional). Slack hooks are built-in with Netlify and could be set up within seconds if you know your Slack incoming webhook URL.

Conclusion

All of the features mentioned above are part of the free Netlify plan. I cannot even imagine the effort invested in providing a seamless experience as it is now. But Netlify doesn’t stop there. They are introducing more and more new and shiny features, like Netlify Dev CLI for local development and deploy cancelations. Netlify has established as an undoubtedly game-changing platform in modern web development of static websites, and it is a big part of the growth and popularity of static sites.

The post My Favorite Netlify Features appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Introducing Netlify Analytics

You work a while on a side project. You think it’s pretty cool! You decide to release it into the world. And then… it goes well. Or it doesn’t go well. Wait, is that right? You forgot to add analytics — it just didn’t cross your mind at the time. Now you’re pretty curious how many people have been visiting the site, but… you’re not sure. Enter Netlify Analytics.

There are so many times where I:

  • Forget to add analytics
  • Don’t want to incur the extra page weight, or
  • I’m concerned with privacy issues

I released a CSS Grid Generator last month and I forgot to add analytics. The release went well, but now it’s a bit of a black box for me as far what happened there or if I need to adjust a release in the future. Now, however, I can enable Netlify Analytics and see into the past without having lost any information. Sweet.

Netlify Analytics doesn’t have a ton of bells and whistles — it’s not meant to be a replacement for super comprehensive marketing tools. But if you want to get some data about your site without adding a lot of scripts, it can be a handy tool.

One really nice thing about it is the accuracy. Since the data is coming from the server, you can have a clear picture of what the server actually served, rather than relying on a third party which might have varied reporting due to things like add blockers that can skew client-side reporting (15% of users are estimated to use tools like Ghostery, for instance), caching, and other factors.

The Analytics Dashboard

The dashboard for each site shows some “at a glance” information:

chart showing some of at a glance information

Then you can dive into more detailed information by specific date:

chart showing by date

There’s a bit of information from top sources and top pages:

chart showing top sources

There’s an area for “Top Resources Not Found”, which shows any pages, images, anything that your visitors are trying and failing to retrieve from your site. When I enabled it on mine, I was able to fix a broken resource that I had long forgotten about.

It’s going to be awesome being able to check how some of my dev projects are doing. But I’m also really excited to take that extra implementation step out of my work. The caveats to keep in mind is that your site needs to be hosted by Netlify in order to use the Analytics tools, and it’s a paid feature. Any site you enable will show up to 90 days (3 billing cycles) in the “Bandwidth used” chart, and up to 30 days in all other charts if it’s old enough, however it could take up to 2 days between when you enable analytics and when your dashboard is calculated and populated.

Under the hood

The analytics dashboard itself is built with React and Highcharts. Highcharts is a JavaScript charting library that includes responsive options and an accessibility module. All of the components consume data from our internal analytics API.

Before development began, we conducted an internal comparison survey of data visualization libraries in order to choose the best one for our needs. We landed on Highcharts over other popular options like d3.js, primarily because it means any engineer at Netlify with JavaScript experience can jump in and contribute, whether they have deep SVG and D3-specific knowledge or not.

While the charts themselves are rendered as SVG elements, Highcharts allows you to render any text inside the graph using HTML, simplifying and speeding our development time and allowing us to use CSS for advanced styling. The Highcharts docs are also top notch and offer a ton of customization options through their declarative API.

We used the Highcharts wrapper for React in order to create reusable React components for each type of graph. The “Top sources,” “Top pages,” and “Top resources not found” cards use a different component that displays a <table> using the data passed in as props.

One of the trickier challenges we encountered on the UI side while building these graphs was displaying dates along the X axis of the area charts in a way that wouldn’t look overwhelming.

Highcharts offers an option to customize the format of an axis label using a JavaScript callback function, so we hooked into that to display every other date as a label. From there, we wrote an algorithm to capture the first date of each month that was being displayed and add the month name into the markup for the label, making the UI a bit cleaner and easier to digest.

Other Analytics Alternatives, with Snippets

If you’d still like to run third-party scripts and other kind of analytics, Netlify has capabilities to add something globally to <head> or <body> tags. This is useful because, depending on how your site is set up, it can be a bit of a pain to add third-party scripts to every page. Plus, sometimes you want to give the ability to change these scripts to someone who doesn’t have access to the repo. Go to the particular site in the dashboard, then SettingsBuild & DeployPost processing.

That’s where you will find Snippet Injection:

Click “Add snippet” and you’ll be able to select whether you want to add the third-party snippet to the <body> or the <head> tag, and you’ll have a change to post your code in HTML. For example, if you need to add Google Analytics, you’d wrap it in a script tag like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-68528-29"></script> <script>   window.dataLayer = window.dataLayer || [];   function gtag(){dataLayer.push(arguments);}   gtag('js', new Date());    gtag('config', 'UA-XXXXX-XX'); </script>

You’ll also name it so that you can keep track of it. If you need to add more later, this is helpful.

That’s it!

You’re off and running with either the new Netlify Analytics offering that’s built-in or a more robust tool.

The post Introducing Netlify Analytics appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

The Power of Serverless v2.0! (Now an Open-Source Gatsby Site Hosted on Netlify)

I created a website called The Power of Serverless for Front-End Developers over at thepowerofserverless.info a little while back while I was learning about that whole idea. I know a little more now but still have an endless amount to learn. Still, I felt like it was time to revamp that site a bit.

For one thing, just like our little conferences website, the new site is a subdomain of this very site:

https://serverless.css-tricks.com/

Why? What’s this site all about?

The whole idea behind the serverless buzzword is a pretty big deal. Rather than maintaining your own servers, which you already buy from some other company, you architect your app such that everything is run on commoditized servers you access on-demand instead.

Hosting becomes static, which is rife with advantages. Just look at Netlify who offer blazing-fast static hosting and innovate around the developer experience. The bits you still need back-end services for run in cloud functions that are cheap and efficient.

This is a big deal for front-end developers. We’ve already seen a massive growth in what we are capable of doing on the front end, thanks to the expanding power of JavaScript. Now a JavaScript developer can be building entire websites from end-to-end with the JAMstack concept.

But you still need to know how to string it all together. Who do you use to process forms? Where do you store the data? What can I use for user authentication? What content management systems are available in this world? That’s what this site is all about! I’d like the site to be able to explain the concept and offer resources, but more importantly, be a directory to the slew of services out there that make up this new serverless world.

The site also features a section containing ideas that might help you figure out how you might use serverless technology. Perhaps you’ll even take a spin making a serverless site.

Design by Kylie Timpani and illustration by Geri Coady

Kylie Timpani (yes, the same Kylie who worked on the v17 design of this site!) did all the visual design for this project.

Geri Coady did all the illustration work.

If anything looks off or weird, blame my poor implementation of their work. I’m still making my way through checklists of improvements as we speak. Sometimes you just gotta launch things and improve as you go.

Everything is on GitHub and contributions are welcome

It’s all right here.

I’d appreciate any help cleaning up copy, adding services, making it more accessible… really anything you think would improve the site. Feel free to link up your own work, although I tend to find that contributions are stronger when you are propping up someone else rather than yourself. It’s ultimately my call whether your pull request is accepted. That might be subjective sometimes.

Before doing anything dramatic, probably best to talk it out by emailing me or opening an issue. There’s already a handful of issues in there.

I suspect companies that exist in this space will be interested in being represented in here somewhere, and I’m cool with that. Go for it. Perhaps we can open up some kind of sponsorship opportunities as well.

Creating with components: A good idea

I went with Gatsby for this project. A little site like this (a couple of pages of static content) deserves to be rendered entirely server-side. Gatsby does that, even though you work entirely in React, which is generally thought of as a client-side technology. Next.js and react-static are similar in spirit.

I purposely wanted to work in JavaScript because I feel like JavaScript has been doing the best job around the idea of architecting sites in components. Sure, you could sling some partials and pass local variables in Rails partials or Nunjucks includes, but it’s a far cry from the versatility you get in a framework like React, Vue or Angular that are designing entirely to help build components for the front end.

The fact that these JavaScript frameworks are getting first-class server-side rendering stories is big. Plus, after the site’s initial render, the site “hydrates” and you end up getting that SPA feel anyway… fantastic. Yet another thing that shows how a JavaScript-focused front-end developer is getting more and more powerful.

As an aside: I don’t have much experience with more complicated content data structures and JAMstack sites. I suspect once you’ve gone past this “little simple cards of data” structure, you might be beyond what front-matter Markdown files are best suited toward and need to get into a more full-fledged CMS situation, hopefully with a GraphQL endpoint to get whatever you need. Ripe space, for sure.

The post The Power of Serverless v2.0! (Now an Open-Source Gatsby Site Hosted on Netlify) appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , ,
[Top]

Netlify Functions for Sending Emails

Let’s say you’re rocking a JAMstack-style site (no server-side languages in use), but you want to do something rather dynamic like send an email. Not a problem! That’s the whole point of JAMstack. It’s not just static hosting. It’s that plus doing anything else you wanna do through JavaScript and APIs.

Here’s the setup: You need a service to help you send the email. Let’s just pick Sparkpost out of a hat. There are a number of them, and I’ll leave comparing their features and pricing to you, as we’re doing something extremely basic and low-volume here. To send an email with Sparkpost, you hit their API with your API key, provide information about the email you want to send, and Sparkpost sends it.

So, you’ll need to run a little server-side code to protect your API key during the API request. Where can you run that code? A Lambda is perfect for that (aka a serverless function or cloud function). There are lots of services to help you run these, but none are easier than Netlify, where you might be hosting your site anyway.

Get Sparkpost ready

I signed up for Sparkpost and made sure my account was all set up and verified. The dashboard there will give you an API key:

Toss that API Key into Netlify

Part of protecting our API key is making sure it’s only used in server-side code, but also that we keep it out of our Git repository. Netlify has environment variables that expose it to functions as needed, so we’ll plop it there:

Let’s spin up Netlify Dev, as that’ll make this easy to work with

Netlify Dev is a magical little tool that does stuff like run our static site generator for us. For the site I’m working on, I use Eleventy and Netlify Dev auto-detects and auto-runs it, which is super neat. But more importantly, for us, it gives us a local URL that runs our functions for testing.

Once it’s all installed, running it should look like this:

In the terminal screenshot above, it shows the website itself being spun up at localhost:8080, but it also says:

◈ Lambda server is listening on 59629

That’ll be very useful in a moment when we’re writing and testing our new function — which, by the way, we can scaffold out if we’d like. For example:

netlify functions:create --name hello-world

From there, it will ask some questions and then make a function. Pretty useful to get started quickly. We’ll cover writing that function in a moment, but first, let’s use this…

Sparkpost has their own Node lib

Sparkpost has an API, of course, for sending these emails. We could look at those docs and learn how to hit their URL endpoints with the correct data.

But things get even easier with their Node.js bindings. Let’s get this set up by creating all the folders and files we’ll need:

/project    ... your entire website or whatever ...    /functions/       /send-email/          package.json          send-email.js

All we need the package.json</code file for is to yank in the Sparkpost library, so <code>npm install sparkpost --save-dev will do the trick there.

Then the send-email.js imports that lib and uses it:

const SparkPost = require('sparkpost'); const client = new SparkPost(process.env.SPARKPOST);  exports.handler = function(event, context, callback) {   client.transmissions     .send({       content: {         from: 'chris@css-tricks.com',         subject: 'Hello, World!',         html:           "<html><body><p>My cool email.</p></body></html>"       },     recipients: [{ address: 'chriscoyier@gmail.com' }]   }); }

You’ll want to look at their docs for error handling and whatnot. Again, we’ve just chosen Sparkpost out of a hat here. Any email sending service will have an API and helper code for popular languages.

Notice line 2! That’s where we need the API key, and we don’t need to hard-code it because Netlify Dev is so darn fancy that it will connect to Netlify and let us use the environment variable from there.

Test the function

When Netlify Dev is running, our Lamba functions have that special port they are running. We’ll be able to have a URL like this to run the function:

http://localhost:34567/.netlify/functions/send-email

This function is set up to run when it’s hit, so we could simply visit that in a browser to run it.

Testing

Maybe you’ll POST to this URL. Maybe you’ll send the body of the email. Maybe you’ll send the recipient’s email address. It would be nice to have a testing environment for all of this.

Well, we can console.log() stuff and see it in the terminal, so that’s always handy. Plus we can write our functions to return whatever, and we could look at those responses in some kind of API testing tool, like Postman or Insomnia.

It works!

I’ll leave it to you to get fancy with it 😉

The post Netlify Functions for Sending Emails appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

It’s pretty cool how Netlify CMS works with any flat file site generator

Little confession here: when I first saw Netlify CMS at a glance, I thought: cool, maybe I’ll try that someday when I’m exploring CMSs for a new project. Then as I looked at it with fresh eyes: I can already use this! It’s a true CMS in that it adds a content management UI on top of any static site generator that works from flat files! Think of how you might build a site from markdown files with Gatsby, Jekyll, Hugo, Middleman, etc. You can create and edit Markdown files and the site’s build process runs and the site is created.

Netlify CMS gives you (or anyone you set it up for) a way to create/edit those Markdown files without having to use a code editor or know about Pull Requests on GitHub or anything. It’s a little in-browser app that gives you a UI and does the file manipulation and Git stuff behind the scenes.

Here’s an example.

Our conferences website is a perfect site to build with a static site generator.

It’s on GitHub, so it’s open to Pull Requests, and each conference is a Markdown file.

That’s pretty cool already. The community has contributed 77 Pull Requests already really fleshing out the content of the site, and the design, accessibility, and features as well!

I used 11ty to build the site, which works great with building out those Markdown files into a site, using Nunjucks templates. Very satisfying combo, I found, after a slight mostly configuration-related learning curve.

Enter Netlify CMS.

But as comfortable as you or I might be with a quick code edit and Pull Request, not everybody is. And even I have to agree that going to a URL quick, editing some copy in input fields, and clicking a save button is the easiest possible way to manage content.

That CMS UI is exactly what Netlify CMS gives you. Wanna see the entire commit for adding Netlify CMS?

It’s two files! That still kinda blows my mind. It’s a little SPA React app that’s entirely configurable with one file.

Cutting to the chase here, once it is installed, I now have a totally customized UI for editing the conferences on the site available right on the production site.

Netlify CMS doesn’t do anything forceful or weird, like attempt to edit the HTML on the production site directly. It works right into the workflow in the same exact way that you would if you were editing files in a code editor and committing in Git.

Auth & Git

You use Netlify CMS on your production site, which means you need authentication so that just you (and the people you want) have access to it. Netlify Identity makes that a snap. You just flip it on from your Netlify settings and it works.

I activated GitHub Auth so I could make logging in one-click for me.

The Git magic happens through a technology called Git Gateway. You don’t have to understand it (I don’t really), you just enable it in Netlify as part of Netlify Identity, and it forms the connection between your site and the Git repository.

Now when you create/edit content, actual Markdown files are created and edited (and whatever else is involved, like images!) and the change happens right in the Git repository.


I made this the footer of the site cause heck yeah.

The post It’s pretty cool how Netlify CMS works with any flat file site generator appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , , ,
[Top]

A Site for Front-End Development Conferences (Built with 11ty on Netlify)

I built a new little site! It’s a site for listing upcoming conferences in the world of front-end web design and development. In years past (like 2017), Sarah Drasner took up this daunting job. We used a form for new conference submissions, but it was still a rather manual task of basically manually editing a blog post. I wanted to keep doing this, as I think it’s valuable to have a simple reference page for conferences in our niche slice of the web, but I wanted the site to be able to live on year after year with lower maintenance-related technical debt.

So this is what I did!

I wanted to get it on GitHub.

So I put it there. Part of the beauty of GitHub is that it opens up the idea of collaboration through pull requests to really anyone in the world. You need to have a GitHub account, but that’s free, and you need to understand Git at least on some minor level (which is a barrier that I’d like to resolve in time), but it invites more collaboration than something like just asking people to email you content and ideas.

I wanted the content in Markdown in the Repo.

The Front Matter format, which is Markdown with some data the the top, is such a useful and approachable format. You need almost zero knowledge, not even HTML, to be able to create/edit a file like this:

Having the actual conference data in the repo means that pull requests aren’t just for design or features; more commonly, they will be for actual conference data. The work of making this site full of all the best conferences is the work of all of us, not just one of us.

At the time of this writing there have already been 30 closed pull requests.

I used 11ty to build the site.

11ty is almost fascinatingly simple. It looks in one directory for what it needs to process or move to another directory. It supports my favorite templating system out of the box: Nunjucks. Plus front matter Markdown like I mentioned above.

I was able to essentially design a card that displays the data we get from the Markdown files, and then build the homepage of the site by looping over those Markdown files and applying the templated card.

11ty is based on Node.js, so while I did have some learning-curve moments, it was comfortable for me to work in. There definitely is configuration for doing the things I wanted to be doing. For example, this is how I had to make a “collection” of conferences in order to loop over them:

config.addCollection("conferences", function(collection) {   let allConferences = collection.getFilteredByGlob("site/conferences/*.md");   let futureConferences = allConferences.filter(conf => {     return conf.data.date >= new Date();   });   return futureConferences; });

The site is hosted on Netlify.

One reason to use Netlify here is that it’s incredibly easy. I made a site site in Netlify by connecting it to the GitHub repo. I told it how to build the site (it’s a single command: eleventy) and where the built site files are (dist), and that’s it. In fact, that’s even part of the repo:

Now whenever I push to the master branch (or accept a pull request into master), the site automatically rebuilds and deploys. Just takes seconds. It’s really amazing.

Better, for each pull request, Netlify makes sure everything is in order first:

My favorite is the deploy preview. It gives you an (obscure) URL that will literally last forever (immutable) and that serves as a look at the built version of this site with that pull request.

So, not only is it extremely easy to use Netlify, but I get a bunch of stuff for free, like the fact that the site is smokin’ fast on their CDNs and such.

I’m also excited that I’ve barely tapped into Netlify’s features here, so there is a lot of stuff I can dig into over time. And I intend to!

I use Zapier to re-build the site every day.

There is a bit of a time-sensitive nature to this site. The point of this site is to reference it for upcoming conferences. It’s less interesting to see past conferences (although maybe we can have a browse-able archive in the future). I like the idea of ripping off past conferences for the homepage. If this was PHP (or whatever), we could do that at runtime, but this is a static site (on purpose). Doing something like this at build time is no big deal (see that code snippet above that only returns conferences past today’s date). But we can’t just waiting around for pull requests to re-build the site, nor do I want to make it a manual thing I need to do every day.

Fortunately, this is easy as pie with Zapier:

Phil Hawksworth took this to the extreme once and built a clock website that rebuilds every minute.


This site wasn’t just an experiment. I’d like to keep it going! If you’re part of running a conference, I’m quite sure it doesn’t hurt to add it to add yours, just so long as it has an enforcable and actionable Code of Conduct, and is within the world of front-end web design and development.

The post A Site for Front-End Development Conferences (Built with 11ty on Netlify) appeared first on CSS-Tricks.

CSS-Tricks

, , , , , ,
[Top]

Netlify Makes Deployments a Cinch

(This is a sponsored post.)

Let’s say you were going to design the easiest way to deploy a static site you can possibly imagine. If I was tasked with that, I’d say, well, it would deploy whenever I push to my master branch, and I’d tell it what command to run to build my site. Or maybe it has its own CLI where I can kick stuff out with as I choose. Or, you know what, maybe it’s so accommodating, I could drag and drop a folder onto it somehow and it would just deploy.

Good news: Netlify is way ahead of me. Netlify can do all those things, and so much more. Your site will be hosted on a CDN so it’s fast as heck. You can roll back to any other deployment because each build is immutable and trivially easy to point to. You can upload a folder of Node JavaScript functions and you can run those so you can do back-end things, like talk to APIs securely. Heck, even your forms can be automatically processed without writing any code at all!

It’s almost shocking how useful Netlify is. I recommend giving it a try, it might be just that empowering tool you need to build that next project you have in mind. 🤔

Direct Link to ArticlePermalink

The post Netlify Makes Deployments a Cinch appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]