How I fixed a sticky element not working in my Next.js / Tailwind CSS app with a grid layout

I started with the following Tailwind CSS / React code and sticky positioning didn't work:

      <div className="grid grid-cols-12 gap-4 min-h-screen mt-16 pt-3">
        <main className="flex flex-col col-start-2 col-span-8">{children}</main>

        <aside className="sticky mt-14 top-20">ASIDE CONTENT</aside>
      </div>

After reading this article I realized I need to apply align-self: start; to my aside element so I added the self-start class to:

      <div className="grid grid-cols-12 gap-4 min-h-screen mt-16 pt-3">
        <main className="flex flex-col col-start-2 col-span-8">{children}</main>

        <aside className="sticky mt-14 top-20 self-start">ASIDE CONTENT</aside>
      </div>

That wasn't enough to solve the problem, though. I asked ChatGPT and he said, among other things:

The sticky element's ancestors must not have overflow properties set to hidden, scroll, or auto.

I checked my code and, bingo, it looks like I had overflow-x: hidden; applied to my body element. Most likely from when I first set up my Next app with create-next-app. I commented it out and sticky positioning started to work.

html,
body {
  max-width: 100vw;
  /* overflow-x: hidden; */
}
reply

Other posts you might like

How I built a chat app using Streams API, Next.JS, Redis and Vercel

Last week I added a chat feature to Sanity. In this article, I'll guide through how I built it using Streams API, Next.js, Redis and Vercel.

Sanity chat

Before we start, a quick disclaimer: there are much better ways to build a chat application, for example by using WebSockets. Vercel unfortunately doesn't support WebSockets and I didn't want to spin a dedicated server, which is why I used Streams API. Using Streams API the way I use it here is most likely not the best use of resources but it works and is a good enough solution for my small scale use. If you're on the same boat, keep reading.

If the chat takes off, I'll have to move it to a dedicated Socket.io server, a serverless WebSocket on AWS, or something similar to reduce costs.

Storing messages in Redis

I use the KV (Redis) database from Vercel to store the last 100 messages. Here is the code used to send and read messages.

import { MAX_CHAT_MESSAGE_LENGTH } from "@/utils";

const MAX_MESSAGES = 100;

export const addChatMessage = async ({
programmingvercelstreams apibackendnext.jsreactredisjavascript
reply

How I fixed @aws-crypto build error

I've been getting the following error when building my Next.js app:

Failed to compile.

./node_modules/.pnpm/@aws-crypto+sha256-js@5.2.0/node_modules/@aws-crypto/sha256-js/build/module/index.js + 12 modules Cannot get final name for export 'fromUtf8' of ./node_modules/.pnpm/@smithy+util-utf8@2.0.2/node_modules/@smithy/util-utf8/dist-es/index.js

I narrowed the source down to the following piece of code:

import { createServerRunner } from "@aws-amplify/adapter-nextjs";
import { AWS_AMPLIFY_CONFIG } from "./utils";
import { cookies } from "next/headers";
import { getCurrentUser } from "aws-amplify/auth/server";

export const { runWithAmplifyServerContext } = createServerRunner({
  config: AWS_AMPLIFY_CONFIG,
});
awsnext.js@aws-cryptoamplifyprogramming
reply

How I implemented slugs on Sanity - a TypeScript code sample

The lack of human-readable slugs on Sanity had bothered me for a while and I finally got around to fixing them last Sunday. The old, slugless URL structure probably wasn't doing me any favors in terms of SEO and user experience. I'm hoping the new format can give Sanity a much needed SEO boost. Plus, I can finally tell which post is which in Google Search Console and Vercel Analytics.

The Result

Before

https://www.sanity.media/p/64c375049f5d6b05859f10c6

After

https://www.sanity.media/p/64c375049f5d6b05859f10c6-delicious-post-workout-milkshake-recipe

Isn't this much clearer?

The Code

When writing the code I had the following goals in mind:

programmingjavascriptmongoosebuilding in publicmongodb
1 comment

How to implement AI vector search and related posts with pgvector

At the end of this tutorial, you should be able to set up your own vector search with text embeddings in a Next.js app. This is a tutorial that mostly consists of coding samples taken directly from the Sanity codebase.

You can see the results right here on Sanity. The related posts section underneath each post is generated with pgvector. So is the search.

The stack I used:

  • Open AI's text-embedding-ada-002 model
  • Next.js
  • Prisma
  • PostgreSQL

Start by setting up the Prisma client:

This step is needed to get Prisma to cooperate with Next.js.

// Setting up prisma
programmingpgvectoraibuilding in publicsql
reply

#My most horrfyingly embarassing and by far toxic trait

I love this website because really only so few of my friends visit it I could just use it to vent to the world. like a little personal diary.

I have this horrible toxic trait of like, sometimes looking up people in my past life to see how their shitty decisions or shitty behavior has led to their lives turning out. Are they as miserable as I imagine they are? sometimes I watch them and through their facial expressions or little clues on their social media and make up little stories about how they're really doing

But I realize this is a toxic trait that I NEED to stop. Doing shit like this will not make my life better, it'll only hold me behind. I need to ignore those people, like they're from my past life. They're dead. Who cares. Work on your own life and trying to drive yourself forward. Why am I obsessed with the dead?

Someone, send me your therapist please. But yeah, definitely need to work on that...where do I start?

confessionstoxic traitsventingtherapysomeone put me on a watch list
reply

How I Managed My Hunger and Improved My Diet

The saying, "You are what you eat," rings true when it comes to our health. The food we consume fuels everything we do, be it work, hobbies, or day-to-day living. Whether it's mental acuity or physical strength you're after, it all traces back to your diet.

If you're still not convinced, let me share my food journey with you.

I didn't always have a problem with my diet. Like many of us, I grew accustomed to my eating habits. If there didn't seem to be any immediate issues with my diet, why should I bother fixing something that wasn't broken?

My dietary journey began when I started researching blue zones – areas where people tend to live exceptionally long lives. My partner and I were intrigued to discover that most residents of these zones followed primarily vegetarian diets, with occasional additions of meat or fish. Noticing this, we decided to incorporate mostly vegetarian foods into our meals. Although I've oscillated between vegetarianism and veganism over the years, I often felt very hungry on these diets. In fact, when I resumed a vegetarian diet, I wasn't feeling my best and noticed increased hunger compared to when I was on an omnivorous diet.

The next phase of my journey was prompted by an unexpected change. Despite not gaining a significant amount of weight after switching my diet, I felt softer, as if I was losing muscle and gaining fat. Dissatisfied with this shift, I turned to the advice of Stephen Zimm, a prof...

healthfitnesssugar addictionhigh protein dietnon restrictive dieting
1 comment

Is there a secure way to use Redis with Vercel?

I spent a couple of hours yesterday trying to find a way to use Redis with Sanity, which currently runs on Vercel. According to Redis docs on security, it is not a good idea to expose a Redis instance directly to the internet:

Redis is designed to be accessed by trusted clients inside trusted environments. This means that usually it is not a good idea to expose the Redis instance directly to the internet or, in general, to an environment where untrusted clients can directly access the Redis TCP port or UNIX socket.

I wanted to use Digital Ocean's trusted sources to restrict the incoming connections to those coming from my Vercel server but looks like that won't be possible because of Vercel's use of dynamic IP addresses. According to Vercel docs:

To ensure your Vercel deployment is able to access the external resource, you should allow connections from all IP addresses. Typically this can be achieved by entering an IP address of (0.0.0.0).

While allowing connections from all IP addresses may be a concern, relying on IP allowlisting for security is generally ineffective and can lead to poor security practices.

To properly secure your database, we recommend using a randomly generated password, stored as an environment variable, at least 32 characters in length, and to rotate this password on a regular basi...

1 comment

A user acquisition conundrum

One of the fastest ways I can attract the first users to Sanity and start getting feedback is by posting about it and engaging on Facebook and Twitter. The thing is, I find them too addictive and full of dark patterns, which is why started Sanity in the first place. I always tell myself I’ll only use them for a specific purpose, or for 15 minutes a day, or only occasionally, and then I gradually get sucked into using them all the time. I start out by visiting once every few days, I check for new posts from a few people I follow, read some AI news, visit groups etc. With time, I find myself using them more and more until several weeks later, I check them throughout the day. This is more of a problem for me with Twitter but, to a lesser extent, also applies to Facebook.

So the question is - how to I get the word out about Sanity without using the addictive social media networks it’s meant to be the alternative to?

I'm focusing on writing content and optimizing SEO for now but it's a slow process. Any tips?

indie makersbuilding in publicseosocial mediasocial media addiction
reply

How to use AWS Amplify Authentication with Next.js Server Actions

No next-auth required:

// amplifyServerUtils.ts

import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import config from '@/amplifyconfiguration.json';

export const { runWithAmplifyServerContext } = createServerRunner({
  config
});
// actions.ts

"use server";
import { cookies } from "next/headers";
programmingawsamplifynext.jsamplify v6cognito
reply

How I Maintained a Regular Exercise Regime for Over 2 Years

Let me tell you a bit about myself. In my other post, I talked about how I went from being a carb-addicted maniac to eating high-protein foods and thriving from it!

Well, another thing you might not know about me, which is a common trait among all of us humans, is the natural tendency we have to avoid exercise. I read 'Exercised' by Daniel Lieberman, and I really recommend this book to anyone else that hates exercise. I found it really motivating and not at all condescending towards those who did not exercise regularly or didn't like it. The long story short is that exercise was something we basically never evolved to do because it expends precious calories. However, as our society evolved and calories became abundant, we, as humans, never really adapted to this as we are still "evolved" to conserve calories. So, knowing this made me feel a lot less guilty about my exercise-aversion.

What really motivated me to start exercising regularly was having a goal that felt genuinely important and came from within me. During the time that I decided to participate in regular exercise, it was during the pandemic, and I was starting to feel sluggish from the lack of movement while being in lockdown. I also was doing something very difficult and mentally taxing at this time: I was learning a new language. I needed to learn it to at least B2 proficiency, fluent in other words. This was not at all an easy task, as any of you w...

healthfitnessexerciseexercised by daniel liebermanvideo games
reply
feedback