From Full-Stack Overload to a Simple Static Site

This is my first blog post, and I want to start with the website itself: why this is my second one, and why I moved away from the first.

Why I Gave Up on My First Website

Since I started working in tech, I’ve been fascinated by system design, especially what it takes to build applications that are scalable, maintainable and efficient. I like apps that follow the Twelve-Factor App (opens in new tab) principles, because I think they’re a solid foundation for high-quality software.

By late 2019, I had some experience from my time at IBM, where I had deployed a few apps. But I wanted to go further and learn about DNS, environments, Docker, caching and more. So I decided to build a portfolio website that used all of them. I knew it was overkill for a portfolio, but I saw it as a chance to learn.

I split the project into a separate backend and frontend, with the backend divided into several services. The final design looked like this:

Architecture of the old site: a React and Bootstrap frontend calling a Node.js and Express backend with repository, badge, cache and email services, which talk to GitHub, Credly, Redis and SendGrid

I built the backend with Node.js and TypeScript. One thing I’m especially proud of is how I organized it into modules on top of Express (opens in new tab). Express doesn’t impose any structure on your API, and the modular layout made the code flexible and easy to maintain. If I built something similar today, I’d probably use NestJS (opens in new tab), which gives you that structure out of the box and would save a lot of time.

Each backend service had one job.

Email Service

The email service handled messages sent from the contact form on the website. It talked directly to SendGrid, a cloud email delivery service, through its SDK.

sendEmail = async (req: Request, res: Response) => {
  try {
    const email: Email = this.service.createEmailContent(req.body)

    if (email != null) {
      const emailResponse = await this.service.sendEmail(email)
      return res.status(HttpStatus.OK).json(emailResponse)
    }

    return res.status(HttpStatus.BAD_REQUEST).end()
  } catch (error) {
    return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: error.message })
  }
}

Repository Service

The repository service returned a paginated, sortable list of my GitHub projects for the website to display.

searchPublicRepos = async (req: Request, res: Response) => {
  try {
    const { text, page, pageSize } = req.query

    const searchReq: IRepositorySearchRequest = {
      text: String(text),
      page: Number(page) || 1,
      pageSize: Number(pageSize) || 10,
      visibility: Visibility.Public,
    }

    const count = await this.service.getPublicRepositoriesCount()
    const totalPages = Math.ceil(count / searchReq.pageSize)
    const repositories: Repository[] = await this.service.searchPublicRepositories(searchReq)
    const paginationResponse = { repositories, page: searchReq.page, pages: totalPages }

    return res.status(HttpStatus.OK).json(paginationResponse).locals.cache(paginationResponse)
  } catch (error) {
    return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: error.message })
  }
}

Badge Service

This one was especially interesting. Over time I earned a few Credly (opens in new tab) badges, including the ones for my AWS certifications, and I wanted them to show up on my website shortly after I earned them, without me doing anything. Credly didn’t offer an API for that, so I scraped their website instead. Luckily, their pages were static and their HTML identifiers were consistent, which made scraping easy.

This endpoint returns every badge that hasn’t expired:

getAllNonExpiredBadges = async (req: Request, res: Response) => {
  try {
    const badges: Badge[] = await this.service.getAllNonExpiredBadges()
    return res.status(HttpStatus.OK).json(badges).locals.cache(badges)
  } catch (error) {
    return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: error.message })
  }
}

If you’re curious how to scrape your own Credly badges, here’s how I did it in Node.js with Cheerio:

class BadgeService {
  protected _$: any = null
  protected configService: ConfigService = new ConfigService()

  public async getAllBadges(): Promise<Badge[]> {
    const badges: Badge[] = []

    const profile = this.configService.getAcclaimProfile()
    const response: Response = await fetch(profile.url)

    this._$ = cheerio.load(await response.text())

    this._$(HtmlElement.EarnedBadge).each((i: any, badge: any) => {
      const { title, href } = badge.attribs
      const id = href.split('/')[2]

      const image = this._$(badge).find('div img').attr('src')
      const information = `${profile.badges}/${id}`

      badges.push({ id, title, image, information })
    })

    return badges
  }

  public async getAllNonExpiredBadges(): Promise<Badge[]> {
    const badges: Badge[] = await this.getAllBadges()
    const nonExpired: Badge[] = []

    for (const badge of badges) {
      const informationResponse: Response = await fetch(badge.information)
      const informationHtml: string = await informationResponse.text()
      const informationUI = cheerio.load(informationHtml)

      const expiredText = informationUI(HtmlElement.BadgeExpire).text()

      if (!expiredText.toLowerCase().includes('expired')) {
        nonExpired.push(badge)
      }
    }

    return nonExpired
  }
}

Cache Service

Scraping the same pages over and over is expensive, and that’s where the cache service came in. I deployed a Redis database and wrote an Express middleware that cached responses, mainly for the Credly badges but also for some of the repository endpoints.

class CacheService {
  private static _instance: CacheService

  private client: RedisClient
  private configService: ConfigService = new ConfigService()

  private constructor() {
    this.client = createClient(this.configService.getRedisCredentials())
    this.client.on('ready', () => Logger.info('Redis: Connection success!'))
    this.client.on('error', (error) => Logger.error(`Redis: ${JSON.stringify(error)}`))
  }

  public static get Instance(): CacheService {
    return this._instance || (this._instance = new this())
  }

  public set(key: string, value: any): void {
    this.client.setex(key, 1800, JSON.stringify(value))
  }

  public get(key: string, callback: any) {
    return this.client.get(key, callback)
  }
}

const cacheMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const key = getKeyFromRequest(req)
  const cache = CacheService.Instance

  cache.get(key, (err: Error, data: any) => {
    if (data && !err) {
      Logger.info(`[Redis]: Requested data ${key} found in cache`)
      res.status(HttpStatus.OK).json(JSON.parse(data))
    } else {
      Logger.info(`[Redis]: Not found, saving ${key} to cache`)
      res.locals.cache = (content: any) => cache.set(key, content)
      next()
    }
  })
}

The Frontend

I won’t say much about the frontend. It was a fairly simple React app with a few custom components, styled with Bootstrap, that fetched its data from the backend over HTTP.

Hosting and Shutting It Down

At first, I ran the website with Docker on a Raspberry Pi 4 in my home office. Later I moved it to Heroku, until Heroku ended its free tier and I had to move everything to Render, which was a bit of a hassle.

Despite all the features and the effort I put in, I eventually shut it down. Keeping it running took too much work, and adding anything new, like a blog (which I never got around to), meant building a new service, connecting it to the frontend and building UI components to show the data. I didn’t have the time for that, so I shut down what had started as a fun experiment.

If you want to look at the code, it’s on GitHub: backend (opens in new tab) and frontend (opens in new tab).

Building My New Static Site with Next.js

After thinking it over, I realized what I really wanted was a simple website that let me focus on writing, not on engineering a web application. I just wanted to share my experiences, and a static site was perfect for that.

I knew Next.js was my best bet, since it’s a full-stack framework with great static site generation. I found a template to build on, cleared out its content, deployed it to Vercel (which was easy), pointed my domains at it and added a few pages of my own. It also came with a built-in blog, which is how you’re reading this post. Whenever I have something new to share, I write it, push it to the repository, and it’s live right away.

You can find the code for this website at github.com/andresromerodev/portfolio (opens in new tab).

Building both websites taught me a lot, and I don’t regret any of the time I spent on them. Thanks for reading!

All posts