<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reza Zahedi on Medium]]></title>
        <description><![CDATA[Stories by Reza Zahedi on Medium]]></description>
        <link>https://medium.com/@rezahedi?source=rss-e398bc6bfdb0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kFhVv21DwwUSP4i4kCDMTA.jpeg</url>
            <title>Stories by Reza Zahedi on Medium</title>
            <link>https://medium.com/@rezahedi?source=rss-e398bc6bfdb0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:31:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rezahedi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stunning Embedded Rich Cards with the Astro Markdown Plugin for GitHub Repositories]]></title>
            <link>https://medium.com/@rezahedi/stunning-embedded-rich-cards-with-the-astro-markdown-plugin-for-github-repositories-78b123671f9a?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b123671f9a</guid>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 03:46:42 GMT</pubDate>
            <atom:updated>2024-04-09T04:07:23.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwxqkV15nePR7XsGTvcnpA.png" /></figure><p>I was following dub.co development and specially the dub’s creator, Steven on social media, One day he shared a link to a page that the embedded cards in the content catches my eye. As you can see on the following screenshot the cards for npm package and Github repository shows beautifully more data about them. It was cool and I was like I should impalement that on my website too. It’s more useful show a rich card instead of just give links to repositories or npm packages in my content.</p><h4>The rich and informative embedded Cards</h4><p>As an avid follower of <a href="https://dub.co/customers/raycast">open source dub.co’s development</a>, I was checking a page then instantly something captured my attention. The page featured embedded cards within its content, showcasing a information about npm packages and GitHub repositories like the downloads, stars or forks count and etc. as you can see in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X61HmiRXSD9Jhio49v38-w.png" /><figcaption>Screenshot from Dub.co/customers</figcaption></figure><p>I was impressed by how elegantly these cards presented additional data about that repository or the npm package. It dawned on me that integrating such rich cards into my own website would enhance its aesthetics and provide more utility to my audience. After all, presenting rich cards offers a far more informative and engaging experience compared to simply providing links to another page within my content.</p><p>After searching a lot for a suitable plugin or existing codebase to avoid reinventing the wheel, I came up to do it by myself.</p><h4>Astro and rehype</h4><p>FYI, I used Astro to build my website and fortunately Astro uses rehype as part of its markdown stack, which makes it easy to add plugins to the content processing to restructure or transform the page’s content.</p><blockquote>Rehype combines the unified content processor and hast html AST to represent an html document as a tree structure. This tree structure can be walked and transformed by a series of plugins.</blockquote><p>So I need to build a rehype plugin to look through the markdown and find the Github repositories URLs, make a asynchronous API call to Github for repository’s data and finally create the card’s HTML structure and insert within the page’s content.</p><p>I did some research about rehype’s plugins and found <a href="https://www.larrymyers.com/posts/how-to-create-an-astro-markdown-plugin/">Larry Myers article</a>, He described the process of building a plugin for Astro really clear and straight forward. I literally just followed his instruction.</p><blockquote>A rehype plugin is a function that receives configuration and returns a function that may transform the tree representing the html output of the markdown document.</blockquote><h4>How to add a new plugin to Astro</h4><p>Here’s the base structure of a rehype plugin in Astro:</p><pre>import type { RehypePlugin } from &quot;@astrojs/markdown-remark&quot;;<br>import { visit } from &quot;unist-util-visit&quot;;<br><br>export const myPlugin: RehypePlugin = () =&gt; {<br>  return (tree) =&gt; visit(tree, (node) =&gt; {<br>    // TODO: Find the node and Transfom it.<br>  });<br>};</pre><p><em>Now add the </em><em>myPlugin to </em><em>astro.config.ts</em></p><pre>export default defineConfig({<br>  site: &quot;https://www.mysite.com/&quot;,<br>  markdown: {<br>    rehypePlugins: [myPlugin],<br>  },<br>});</pre><h4>Logic of our plugin</h4><p>Now I just need to create the logic of my transformer plugin as listed below:</p><ul><li>Determine if a tree node is an element.</li><li>Check if the element is an anchor tag.</li><li>Check if the anchor tag has an href attribute.</li><li>Check if the href url is the same as the anchor’s child. (I will describe why)</li><li>Do the API call using the founded url.</li><li>Create the card’s HTML tree or DOM using the fetched data.</li><li>Replace the anchor node with the created card.</li></ul><p>We don’t want to replace/transform any anchor or &lt;a href=&quot;https://github.com/...&quot;&gt; that we have in our markdown. We just want to transform those Github URLs that simple added as a new line into our markdown, Please check the following example:</p><p><em>my-astro-page.md</em></p><pre>---<br>title=&quot;Title of the Page&quot;<br>description=&quot;...&quot;<br>publishDate=&quot;Sep, 18 2024&quot;<br>---<br><br>This is a markdown format page.<br>Have you ever heard of [dub](https://github.com/dubco/dub)?<br>It&#39;s a realy cool open source project.<br><br>https://github.com/dubinc/dub<br><br>Our plugin should only change the abow URL with the rich card!</pre><h4>First step: Find Github URLs</h4><p>With the help of Larry’s article I created the base and first step of our function which is finding the right element:</p><pre>import type { RehypePlugin } from &quot;@astrojs/markdown-remark&quot;;<br>import { visit } from &quot;unist-util-visit&quot;;<br>import type { Element } from &quot;hast&quot;;<br>import { h } from &quot;hastscript&quot;;<br><br>export const myPlugin: RehypePlugin = () =&gt; {<br>  <br>  return async (tree) =&gt; {<br>    const repos = [] as any;<br><br>    // Find all anchor elements that are link to a GitHub repo<br>    visit(tree, &quot;element&quot;, (node) =&gt; {<br>      if (node.type != &quot;element&quot;) return;<br><br>      const anchorElement = node as Element;<br>      if ( isAnchor(anchorElement) &amp;&amp; isGithubRepoURL(getURL(anchorElement)) ) {<br>        repos.push(node)<br>      }<br>    });<br>    if (repos.length == 0) return;<br><br>    // TODO: Fetch data for each repo and create the GitHub card<br><br>  }<br>}<br><br><br>// Check if the element is an anchor<br>// And the only text child is the same as the href<br>// ex: &lt;a href=&quot;http://example.com&quot;&gt;http://example.com&lt;/a&gt;<br>const isAnchor = (element: Element) =&gt; {<br>  return<br>    element.tagName == &quot;a&quot;<br>    &amp;&amp; element.properties<br>    &amp;&amp; &quot;href&quot; in element.properties<br>    &amp;&amp; element.children.length == 1<br>    &amp;&amp; element.children[0].type == &#39;text&#39;<br>    &amp;&amp; element.children[0].value == element.properties[&quot;href&quot;];<br>}<br><br>const getURL = (element: Element) =&gt; {<br>  if ( !element.properties || !element.properties[&quot;href&quot;] ) return &quot;&quot;;<br><br>  return element.properties[&quot;href&quot;].toString();<br>};<br><br>const isGithubRepoURL = (url: string) =&gt; {<br>  return /^https:\/\/(www\.)?github.com\/[a-zA-Z0-9-_\.]+\/[a-zA-Z0-9-_\.]+$/.test( url );<br>};</pre><h4>Next step: Call Github API asynchronously</h4><p>Next step is to call the Github API and fetch data and it should be async.</p><p>At first I thought whenever link element matched in content, then asynchronously call the API and replace the link node with the card tags and data. but it didn’t work because visit(tree, “element”, (node)=&gt;{}) from unist-util-visit doesn’t return promise.</p><p>Again I got stuck and after discussing it with ChatGPT! and searching on Google, finally find a helpful <a href="https://github.com/syntax-tree/unist-util-visit-parents/issues/8#issuecomment-1413405543">comment of Titus</a> that described how to do async, by split the work up in two stages: first find things then transform things! 🎉</p><p>Here is my final version and it work perfectly:</p><pre>import type { RehypePlugin } from &quot;@astrojs/markdown-remark&quot;;<br>import { visit } from &quot;unist-util-visit&quot;;<br>import type { Element } from &quot;hast&quot;;<br>import { h } from &quot;hastscript&quot;;<br><br>export const myPlugin: RehypePlugin = () =&gt; {<br>  <br>  return async (tree) =&gt; {<br>    const repos = [] as any;<br><br>    // Find all anchor elements that are link to a GitHub repo<br>    visit(tree, &quot;element&quot;, (node) =&gt; {<br>      if (node.type != &quot;element&quot;) return;<br><br>      const anchorElement = node as Element;<br>      if ( isAnchor(anchorElement) &amp;&amp; isGithubRepoURL(getURL(anchorElement)) ) {<br>        repos.push(node)<br>      }<br>    });<br>    if (repos.length == 0) return;<br><br>    // Fetch data for each repo and create a GitHub card<br>    const promises = []<br>    for (const repo of repos) {<br>      const url = getURL(repo);<br>      const repoPathname = url.split(&quot;github.com/&quot;)[1];<br>      promises.push(fetch(`https://api.github.com/repos/${repoPathname}`).then(async (res) =&gt; {<br>        if(res.status !== 200) return;<br><br>        const data = await res.json()<br><br>        const [ownerSlug, repoSlug] = repoPathname.split(&quot;/&quot;);<br>        const repoCard = h(&quot;a.github-card&quot;, { href: url, target: &quot;_blank&quot; }, [<br>          h(&quot;img&quot;, { src: data.owner.avatar_url, alt: data.owner.login }),<br>          h(&quot;h3&quot;, [<br>            h(&quot;text&quot;, ownerSlug+&quot;/&quot;),<br>            h(&quot;b&quot;, repoSlug)<br>          ]),<br>          h(&quot;p&quot;, data.description),<br>          h(&quot;div&quot;, [<br>            h(&quot;div&quot;, [<br>              h(&quot;b&quot;, data.stargazers_count),<br>              h(&quot;span&quot;, &quot;Stars&quot;),<br>            ]),<br>            h(&quot;div&quot;, [<br>              h(&quot;b&quot;, data.forks_count),<br>              h(&quot;span&quot;, &quot;Forks&quot;),<br>            ]),<br>          ])<br>        ]);<br>        repo.tagName = &quot;div&quot;;<br>        repo.children = [repoCard];<br>      }))<br>    }<br>    await Promise.all(promises)<br>  }<br>}</pre><h4>The final result</h4><p>The result for each Github’s cards will be like this:</p><pre>&lt;div&gt;<br>  &lt;a href=&quot;{repository-url}&quot; class=&quot;github-card&quot; target=&quot;_blank&quot;&gt;<br>    &lt;img src=&quot;{repository-owner-avatar-image-url}&quot; alt=&quot;{repository-name}&quot; /&gt;<br>    &lt;h3&gt;{repository-owner-slug}/&lt;b&gt;{repository-slug}&lt;/b&gt;&lt;/h3&gt;<br>    &lt;p&gt;{description}&lt;/p&gt;<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;b&gt;{stars-count}&lt;/b&gt;<br>        &lt;span&gt;Stars&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;b&gt;{forks-count}&lt;/b&gt;<br>        &lt;span&gt;Forks&lt;/span&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/a&gt;<br>&lt;/div&gt;</pre><p>And here a screenshot of my website after applying styles to the card:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwxqkV15nePR7XsGTvcnpA.png" /></figure><p>In this approach, there’s a caveat to consider: rehype plugins and markdown processing occur solely during build time in Astro. So, the resulting output is static, meaning that repository data — such as stars, forks, and other metrics — remains unchanged over time. To ensure data accuracy and freshness, one must rebuild the Astro project periodically!😁</p><p>Alternatively, another method to create these embedded cards is developing a React component to do the API call in client-side. This component can be imported and utilized within your page’s content as an Astro Island, by adding the client:load directive. However, to import components it’s important to note that requires your page’s content files to be in either .astro or .mdx format, excluding the use of .md files.</p><p>Please let me know what you think or if you have any question in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b123671f9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Guide: Next-Auth Email Login Setup & use Resend to send verification email]]></title>
            <link>https://medium.com/@rezahedi/quick-guide-next-auth-email-login-setup-use-resend-to-send-verification-email-504fb2548e43?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/504fb2548e43</guid>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[resend]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 08:35:15 GMT</pubDate>
            <atom:updated>2024-01-31T08:35:15.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Screenshot from StreakUp’s signin page" src="https://cdn-images-1.medium.com/max/1024/1*ljXPzDhcBkATxl4ID4KW5Q.png" /><figcaption>Screenshot from StreakUp’s signin page</figcaption></figure><p>I’m currently working on my small portfolio project, which is a habit tracker application. It’s called <a href="https://streakup.vercel.app/">StreakUp</a> and you can try it out or take a look at its <a href="https://github.com/rezahedi/streakup">github repository</a>.</p><p>As I love to try out various features on it to gain more experience with different services, packages, or APIs, so I started implementing Next-Auth authentication over it and then wanted to add an email login option too, in addition to the Google and Github OAuth providers, Here is how I did this.</p><p>Before we dive into the implementation details, make sure you have set up your Next.js application with Next-Auth for authentication.</p><h4>Email Provider configuration</h4><p>Next-Auth has different providers and one of them is <a href="https://next-auth.js.org/providers/email">Email Provider</a>, which uses email to send “magic links” that can be used to sign in without a password, you will likely have seen these if you have used services like Slack before. The email provider will send an email with a Verification Token embedded in a URL as a parameter inside the body of the email to the email address provided.</p><p>The Email Provider comes with a set of default options that we can override any of the options to suit our use case.</p><pre>// app/api/auth/[...nextauth].js<br>import { NextAuthOptions } from &quot;next-auth&quot;;<br>import EmailProvider from &#39;next-auth/providers/email&#39;;<br><br>const authOptions: NextAuthOptions = {<br>  ...<br>  providers: [<br>    ...<br>    EmailProvider({<br>      from: &#39;noreply@example.com&#39;,<br>      // Custom sendVerificationRequest() function<br>      sendVerificationRequest({<br>        identifier: email, url, provider: { from }<br>      }) {<br>        /* TODO: Send login email functions here */<br>      },<br>    }),<br>  ],<br>}</pre><h4>Setup Resend Email API</h4><p>As we don’t want to use an SMTP server to send out emails, <a href="https://resend.com/">Resend</a> will handle that for us. Resend is a developer-first email API service provider and has a clean REST API and it’s convenient to use it in any project.</p><p>Head to Resend.com, open up an account, verify your domain, and create an API key, then save it in .env file.</p><pre># .env<br>RESEND_API_KEY = &quot;&quot;</pre><p>Install the Resend Node.js package:</p><pre>npm install resend</pre><h4>Customizing Verification Emails</h4><p>To customize the sign-in email to our specific requirements, it is essential to pass a custom function as the sendVerificationRequest option to EmailProvider(). To initiate this process, let’s begin by constructing the function in a separate file first.</p><pre>// resend.ts<br>import { Resend } from &#39;resend&#39;;<br>import { SendVerificationRequestParams } from &#39;next-auth/providers&#39;;<br><br>export const sendVerificationRequest = async (<br>  params: SendVerificationRequestParams,<br>) =&gt; {<br>  let { identifier: email, url, provider: { from } } = params;<br>  try {<br>    const resend = new Resend( process.env.RESEND_API_KEY! );<br>    await resend.emails.send({<br>      from: from,<br>      to: email,<br>      subject: &#39;Login Link to your Account&#39;,<br>      html: &#39;&lt;p&gt;Click the magic link below to sign in to your account:&lt;/p&gt;\<br>             &lt;p&gt;&lt;a href=&quot;&#39; + url + &#39;&quot;&gt;&lt;b&gt;Sign in&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;&#39;,<br>    });<br>  } catch (error) {<br>    console.log({ error });<br>  }<br>};</pre><p>After creating the custom function, it’s time to integrate it into Next-Auth configuration options as sendVerificationRequest:</p><pre>// app/api/auth/[...nextauth].js<br>import { NextAuthOptions } from &quot;next-auth&quot;;<br>import EmailProvider from &#39;next-auth/providers/email&#39;;<br>import { sendVerificationRequest } from &#39;./resend.ts&#39;<br><br>const authOptions: NextAuthOptions = {<br>  ...<br>  providers: [<br>    ...<br>    EmailProvider({<br>      from: &#39;noreply@example.com&#39;,<br>      // Custom sendVerificationRequest() function<br>      sendVerificationRequest,<br>    }),<br>  ],<br>}</pre><p>It’s time to put the code to the test. When users enter their email address, they should promptly receive an email containing a “magic link” that facilitates seamless sign-in to the application.</p><p>I know the template of the login email looks so simple, Resend offers another fantastic collection of components called <a href="https://react.email/">react-email</a>, which are built for creating beautiful emails using React and TypeScript, and don’t need to worry about email formats (HTML or Text) or deal with inline CSS styling, and have the flexibility to integrate Tailwind CSS. I plan to use it in my project too.</p><p>Finally, let me know if you have any questions or run into any issues. And hey, if you’re curious to dive deeper, feel free to check out the StreakUp source code on <a href="https://github.com/rezahedi/streakup">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=504fb2548e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Table of contents in Astro and sectionize the Markdown content]]></title>
            <link>https://medium.com/@rezahedi/how-to-build-table-of-contents-in-astro-and-sectionize-the-markdown-content-78bee84e6a7f?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/78bee84e6a7f</guid>
            <category><![CDATA[astro-build]]></category>
            <category><![CDATA[intersection-observer]]></category>
            <category><![CDATA[position-sticky]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 03:17:08 GMT</pubDate>
            <atom:updated>2024-01-23T03:52:58.216Z</atom:updated>
            <content:encoded><![CDATA[<p>As I explored my <a href="https://astro.build/">Astro</a> website’s inner pages, I noticed their simplicity. To enhance the user experience and make navigation more accessible, I decided to add a sticky table of contents (TOC) in the empty column on the right side of the page’s content.</p><figure><img alt="Example screenshot of a post" src="https://cdn-images-1.medium.com/max/1024/1*ohdbJDlS9zaW5BtxCN_YFg.png" /><figcaption>Example screenshot of a blog post from my website</figcaption></figure><h3>Creating Table of Contents component</h3><p>It’s a straightforward process — access the list of headings, create the Table of Contents (TOC) component, pass the headings to it, integrate the component into your layout, and finally, apply the necessary styling to achieve a visually appealing and sticky effect.</p><h4>Retrieving the headings prop in Astro layouts or components</h4><p>Accessing the list of headings in Astro is conveniently facilitated by passing all the headings, along with frontmatter values, as props to your layouts or components. The following code serves as the foundation for an Astro layout, showing how to obtain both frontmatter values and headings:</p><pre>---<br>// ./src/layouts/BlogPost.astro<br>export interface Props {<br>  content: {<br>    title: string;<br>  },<br>  headings: {<br>    slug: string;<br>    text: string;<br>    depth: number;<br>  }[]<br>}<br><br>const {<br>  content: { title },<br>  headings<br>} = Astro.props;<br>---<br>&lt;html&gt;<br>&lt;body&gt;<br><br>  &lt;h2&gt;{title}&lt;/h2&gt;<br><br>  &lt;!-- TOC --&gt;<br>  &lt;slot /&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>If you are interested to what information could be passed through Astro.props check Astro’s documentations for <a href="https://docs.astro.build/en/core-concepts/layouts/#markdown-layout-props">Markdown Layout Props</a>.</p><p>The headings prop is a flat array of markdown headings object, but each object includes a depth property that specifies the level of depth for sub-headings, here is an example array of headings objects:</p><pre>[<br>  { text: &#39;First Heading&#39;,       slug: &#39;first-heading&#39;,       depth: 2 },<br>  { text: &#39;Sub Heading&#39;,         slug: &#39;sub-heading&#39;,         depth: 3 },<br>  { text: &#39;Another Sub Heading&#39;, slug: &#39;another-sub-heading&#39;, depth: 3 },<br>  { text: &#39;Second Heading&#39;,      slug: &#39;second-heading&#39;,      depth: 2 },<br>  { text: &#39;Last Heading&#39;,        slug: &#39;last-heading&#39;,        depth: 2 },<br>]</pre><h4>Turning the flat array to a nested array</h4><p>Now that we have the list of headings from the markdown content, the next step is to convert it to a nested array in order to have a hierarchy TOC with indented items by utilizing the depth property of each object, I got the following code from <a href="https://kld.dev/building-table-of-contents/#building-a-nested-table-of-contents-array">Kevin Drum’s post</a>:</p><pre>// github.com/rezahedi/rezahedi.dev/blob/main/src/components/TOC.astro<br>function buildHierarchy(headings: any)<br>{<br>  const toc: any[] = [];<br>  const parentHeadings = new Map();<br>  <br>  if (!headings)<br>    return toc;<br>  <br>  headings.forEach((h: any) =&gt; {<br>    const heading = { ...h, subheadings: [] };<br>    parentHeadings.set(heading.depth, heading);<br>    // Change 2 to 1 if your markdown includes your &lt;h1&gt;<br>    if (heading.depth === 2) {<br>      toc.push(heading);<br>    } else {<br>      parentHeadings.get(heading.depth - 1).subheadings.push(heading);<br>    }<br>  });<br>  return toc;<br>}</pre><p>The buildHierarchy(headings) function takes a flat array of headings as input and returns a nested array. Here is an example of the result:</p><pre>[<br>  {<br>    text: &#39;First Heading&#39;, slug: &#39;first-heading&#39;, depth: 2,<br>    subheadings:[<br>      {<br>        text: &#39;Sub Heading&#39;, slug: &#39;sub-heading&#39;, depth: 3,<br>        subheadings:[]<br>      },<br>      {<br>        text: &#39;Another Sub Heading&#39;, slug: &#39;another-sub-heading&#39;, depth: 3,<br>        subheadings:[]<br>      },<br>    ]<br>  },<br>  {<br>    text: &#39;Second Heading&#39;, slug: &#39;second-heading&#39;, depth: 2, subheadings:[]<br>  },<br>]</pre><h4>Building TOC component</h4><p>Now create /components/TOC.astro component, use buildHierarchy(headings) function to create new nested array of headings add then build the base structure of our TOC component. in order to render the indented items as each headings may have subheadings we need another but recursive component (TOCHeading.astro) that reference itself from within itself! below is the TOC.astro component:</p><pre>---<br>// github.com/rezahedi/rezahedi.dev/blob/main/src/components/TOC.astro<br>import TOCHeading from &#39;@components/TOCHeading.astro&#39;;<br><br>const { headings } = Astro.props;<br><br>const toc = buildHierarchy(headings);<br><br>function buildHierarchy(headings: any) {<br>  // ...<br>}<br>---<br>{toc &amp;&amp; toc.length &gt; 0 &amp;&amp; (<br>  &lt;nav class=&quot;article-toc&quot;&gt;<br>    &lt;ul&gt;<br>      {toc.map((heading) =&gt; (<br>        &lt;TOCHeading heading={heading} /&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  &lt;/nav&gt;<br>)}</pre><p>The TOCHeading.astro component will make each indented item for us by using subheadings[] property. In Astro in order to call a component within itself you can use Astro.self instead of the component’s name:</p><pre>---<br>// github.com/rezahedi/rezahedi.dev/blob/main/src/components/TOCHeading.astro<br>const { heading } = Astro.props;<br>---<br>&lt;li&gt;<br>  &lt;a href={&#39;#&#39; + heading.slug}&gt;<br>    {heading.text}<br>  &lt;/a&gt;<br>  {heading.subheadings.length &gt; 0 &amp;&amp; (<br>    &lt;ul&gt;<br>      {heading.subheadings.map((subheading: any) =&gt; (<br>        &lt;Astro.self heading={subheading} /&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  )}<br>&lt;/li&gt;</pre><h4>Using TOC component in the layout</h4><p>Now, let’s integrate our TOC component into the blog layout that I believe it’s SEO beneficial to position it before the main content:</p><pre>---<br>// github.com/rezahedi/rezahedi.dev/blob/main/src/layouts/BlogPost.astro<br>import TOC from &#39;@components/TOC.astro&#39;;<br><br>export interface Props {<br> content: {<br>  title: string;<br> },<br> headings: {<br>  slug: string;<br>  text: string;<br>  depth: number;<br> }[]<br>}<br><br>const {<br>  content: { title },<br>  headings<br>} = Astro.props;<br>---<br>&lt;html&gt;<br>&lt;body&gt;<br>  &lt;article&gt;<br>    &lt;h2&gt;{title}&lt;/h2&gt;<br><br>    {headings &amp;&amp; headings.length &gt; 0 &amp;&amp; (<br>      &lt;nav class=&quot;article-toc&quot;&gt;<br>        &lt;h3&gt;Table of Content&lt;/h3&gt;<br>        &lt;TOC headings={headings} /&gt;<br>      &lt;/nav&gt;<br>    )}<br><br>    &lt;div class=&quot;article-content&quot;&gt;<br>      &lt;slot /&gt;<br>    &lt;/div&gt;<br><br>  &lt;/article&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>To make the TOC &lt;nav&gt; element sticky, you only need to apply two styles:</p><pre>.article-toc{<br>  position:sticky;<br>  top:0<br>}</pre><h3>Separating Markdown content into sections</h3><p>Upon completing the TOC, I found it desirable to highlight headings associated with each section of content currently in the browser viewport. However, I observed that my content lacks sectionizing that encompass both the heading and its subsequent content.</p><h4>Installing the plugin package and configuring Astro</h4><p>By default, Astro don’t sectionize the content. However, after doing some research, I discovered that Astro provides the tools like <a href="https://github.com/rehypejs/rehype">rehype</a> or <a href="https://github.com/remarkjs/remark">remark</a>, allowing to customize the process of markdown content formatting by <a href="https://docs.astro.build/en/guides/integrations-guide/mdx/#extendmarkdownconfig">extending markdown config in Astro</a>. To achieve <strong>content sectionization</strong> we need to find a suitable plugin for our project. While you can explore other plugins in the rehype or remark plugins list, I’ve chosen and installed the following one:</p><pre>npm i -D @hbsnow/rehype-sectionize</pre><p>Then by importing this package, we can customize Astro Markdown configuration options by setting the rehypePlugins in markdown property in astro.config.mjs Astro configuration file.</p><p><strong>I made a mistake</strong> by placing rehypePlugins inside integrations:[mdx()] instead of markdown:{} and spend hours debugging and wondering why on earth the plugin wasn’t working. It was only after coming across <a href="https://www.thomasledoux.be/blog/create-blog-astro-mdx#adding-reading-time-for-blog-posts">this post</a> that I realized my stupid error.</p><pre>// github.com/rezahedi/rezahedi.dev/blob/main/astro.config.mjs<br>import { defineConfig } from &#39;astro/config&#39;;<br>// ...<br>import sectionize from &#39;@hbsnow/rehype-sectionize&#39;;<br><br>export default defineConfig({<br>  // ...<br>  markdown:{<br>    rehypePlugins: [sectionize],<br>  },<br>  // ...<br>});</pre><p>Now restart your dev server and inspect your blog post source to see the result, each headings and the following subsequent should wrapped between a &lt;section&gt; tag like the following example:</p><pre>&lt;!-- Pre sectionize plugin --&gt;<br>&lt;h2 id=&quot;first-heading-title&quot;&gt;First Heading Title&lt;/h2&gt;<br>&lt;p&gt;Some paragraph content&lt;/p&gt;<br>&lt;p&gt;Some paragraph content&lt;/p&gt;<br>&lt;h2 id=&quot;second-heading-title&quot;&gt;Second Heading Title&lt;/h2&gt;<br>&lt;p&gt;Some paragraph content&lt;/p&gt;<br>&lt;p&gt;Some paragraph content&lt;/p&gt;<br><br>&lt;!-- Sectionized result --&gt;<br>&lt;section class=&quot;heading&quot; data-heading-rank=&quot;2&quot;&gt;<br>  &lt;h2 id=&quot;first-heading-title&quot;&gt;First Heading Title&lt;/h2&gt;<br>  &lt;p&gt;Some paragraph content&lt;/p&gt;<br>  &lt;p&gt;Some paragraph content&lt;/p&gt;<br>&lt;/section&gt;<br>&lt;section class=&quot;heading&quot; data-heading-rank=&quot;2&quot;&gt;<br>  &lt;h2 id=&quot;second-heading-title&quot;&gt;Second Heading Title&lt;/h2&gt;<br>  &lt;p&gt;Some paragraph content&lt;/p&gt;<br>  &lt;p&gt;Some paragraph content&lt;/p&gt;<br>&lt;/section&gt;</pre><h4>Observing sections to highlight related headings in TOC</h4><p>It’s time to add our final piece of client-side Javascript code to highlight TOC headings that its related &lt;section&gt; is in the browser viewport by adding a .active class. It can be done using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer API</a> by attaching an observer to each sections tag element.</p><pre>// github.com/rezahedi/rezahedi.dev/blob/main/src/layouts/BlogPost.astro<br>// Source: https://kld.dev/toc-animation/#marking-active-links<br>function addIntersectionObserver()<br>{<br>  const observer = new IntersectionObserver((sections) =&gt; {<br>    sections.forEach((section) =&gt; {<br>      const heading = section.target.querySelector(&#39;h2, h3, h4, h5&#39;);<br>      if (!heading) return;<br>      const id = heading.getAttribute(&#39;id&#39;);<br><br>      // Get the link to this section&#39;s heading<br>      const link = document.querySelector(`nav.article-toc li a[href=&quot;#${id}&quot;]`);<br>      if (!link) return;<br><br>      // Add/remove the .active class based on whether the<br>      // section is visible<br>      const addRemove = section.intersectionRatio &gt; 0 ? &#39;add&#39; : &#39;remove&#39;;<br>      link.classList[addRemove](&#39;active&#39;);<br>    });<br>  });<br><br>  document.querySelectorAll(&#39;.article-content section&#39;).forEach((section) =&gt; {<br>    observer.observe(section);<br>  })<br>}</pre><p>That’s it, you can check my <a href="https://rezahedi.dev/">website</a> for the result. I’ve also included links at the beginning of each code snippet to the corresponding file To my <a href="https://github.com/rezahedi/rezahedi.dev">GitHub project</a> for a more in-depth exploration of the code. Feel free to drop any questions or comments. 😬</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bee84e6a7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js issue of redirect in server actions with unmounting intercepting route or modal from the UI]]></title>
            <link>https://medium.com/@rezahedi/next-js-issue-of-redirect-in-server-actions-with-unmounting-intercepting-route-or-modal-from-the-ui-62b7a9702b7f?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/62b7a9702b7f</guid>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 00:34:17 GMT</pubDate>
            <atom:updated>2023-09-20T00:35:10.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEKEahnowNxTKHFg36hcRQ.png" /><figcaption><a href="https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes">Next.js Intercepting Routes</a></figcaption></figure><p>I was working on my <a href="https://github.com/rezahedi/nextjs-nextauth-starter">Next.js NextAuth starter template</a> to add simple CRUD features by using Next.js’s 13 new App Routing, I tried to add create and edit operations by implementing intercepting route to have my forms popup in overlays modal when users click on Create New or Edit link. I wanted the link to open the form either in a popup modal or in a new page. Everything works fine except for the redirect(path) in my server actions! It updates the page’s route, which means the page gets redirected, but in the new route, my modal is still there and does not unmount! It’s weird, You can read more about this issue on the <a href="https://github.com/vercel/next.js/issues/52837">Next.js Github issues page</a> and <a href="https://github.com/vercel/next.js/issues/49662">here</a>.</p><p>If you are reading this, it means you have faced what I have experienced, In the following paragraphs you’ll see what solution I’ve come up with.</p><h4>The Issue</h4><p>I build a route with containing a form in /create/page.tsx route and a masked URL or modal for it /@modal/(.)create/page.tsx then added my createAction server action to the form.</p><pre>// source code for /create/page.tsx<br>import {redirect} from &#39;next/navigation&#39;<br><br>export default function Home(){<br>  const async function createAction(data: FormData){<br>    &quot;use server&quot;;<br>    // Do server action here, like inserting passed form data to database<br>    redirect(&quot;/list&quot;);<br>  }<br>  return (<br>    &lt;form action={createAction}&gt;<br>      &lt;input name=&#39;title&#39; /&gt;<br>      &lt;input type=&#39;submit&#39; /&gt;<br>    &lt;/form&gt;<br>  )<br>}<br><br><br><br>// Source code for /@modal/(.)create/page.tsx<br>import {redirect} from &#39;next/navigation&#39;<br>import Modal from &#39;@/components&#39;<br><br>export default function Home(){<br>  const async function createAction(data: FormData){<br>    &quot;use server&quot;;<br>    // Do server action here, like inserting passed form data to database<br>    redirect(&quot;/list&quot;);<br>  }<br>  return (<br>    &lt;Modal&gt;<br>      &lt;form action={createAction}&gt;<br>        &lt;input name=&#39;title&#39; /&gt;<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/Modal&gt;<br>  )<br>}</pre><p>Everything straightforward as Next.js documentation and provided examples. Opening /create route directly in browser should works fine and load the whole form’s page directly, after filling and submitting the form, the server action should triggered and the redirect() is going to change the route to our desire new path. But in opened /create as a overlay modal, the redirect() don’t unmount modal, even though the redirect will update the page’s route to the new path and the content of page will change too. But the modal will sticks to the page and does not unmount!</p><p>In a perfect way, It should does call the used server action in my form, then server action run the redirect function, the page’s route update to /list in my case and modal should be gone.</p><p>I was like, what’s the issue with my codes as I’m a beginner, I have googled a lot, checked stackoverflow threads, even asked chatGPT and github copilot chat! but nothing.</p><p>Then I realized why not to handle the form by myself and do the routing in client side, then this solution come to my mind, it may look strange or dump but it works!</p><p>Put your server actions in separate file like actions.ts and remove the redirect function because we are going to handle route changing in the client side.</p><pre>&quot;use server&quot;;<br><br>export function createAction(data: FormData){<br>  // Do server action here, like inserting form&#39;s data into database<br>}</pre><p>And make your create page rendered in client side by adding &quot;use client” directive on top of your codes, as we are going to handle the form submission action so we need to somehow pass the form’s data to our server action function, I used e.currentTarget to get our form’s data and pass it to our server action function createAction():</p><pre>&quot;use client&quot;;<br><br>import Modal from &#39;@/components&#39;<br>import {createAction} from &#39;/actions.ts&#39;<br>import {useRouter} from &quot;next/navigation&quot;;<br><br>export default function Home(){<br>  const router = useRouter();<br><br>  const handleSubmit = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br><br>    const form = e.currentTarget;<br>    const data = new FormData(form);<br><br>    await createAction( formData );<br>    router.back();<br>  };<br><br>  return (<br>    &lt;MyModal&gt;<br>      &lt;form action={create} onSubmit={handleSubmit}&gt;<br>        &lt;input name=&#39;title&#39; /&gt;<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/MyModal&gt;<br>  )<br>}</pre><p>I used client-side router.back() by importing useRouter from next/navigation because we are sure about having browser’s history stack in opened modal situation and we could go back in history that means closing of modal when the form inside of our modal submitted.</p><p>Going back in history stack from an opened modals is fine, but whenever user opens the shareable URL of our page (in my case /create) this page will have empty history stack. If you remember this route did not have any issue with server redirection so we will keep our codes the same, just we need a server action with redirect this time, so I updated our actions.ts with two server actions, one without and the other with redirect function:</p><pre>&quot;use server&quot;;<br><br>export function createAction(data: FormData){<br>  // Do server action here, like inserting passed form data to database<br>}<br><br>// Add the following function to your actions.ts file<br>export function createActionWithRedirect(data: FormData) {<br>  createAction( data );<br>  redirect(&quot;/list&quot;);<br>}</pre><p>I’m not sure if this is the best solution to deal with this situation, but it works for me and you can check <a href="https://github.com/rezahedi/nextjs-nextauth-starter">my project on Github</a>, however if you have any ideas or comments, please share it with me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62b7a9702b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using NextAuth authentication provider in Next.js 13 App Router]]></title>
            <link>https://medium.com/@rezahedi/using-nextauth-authentication-provider-in-next-js-by-app-router-f50cb23282c9?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50cb23282c9</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[app-router]]></category>
            <category><![CDATA[user-authentication]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 21:04:02 GMT</pubDate>
            <atom:updated>2023-08-04T19:57:45.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aa5XR5QtS4UqntK_Y1t4sA.png" /></figure><p>Authentication is a critical part of any app. When you’re building an app, you’ll need to implement user authentication. To make things easier, I decided to create an authentication system using Next.js 13’s new App Router with the help of NextAuth as my starter template. This way, I can use it across all my next applications.</p><p>In this article, I’ll walk you through the basic steps, but if you are interested to learn more about Next.js 13 routing, <a href="https://github.com/rezahedi/nextjs-nextauth-starter">my project’s source code are available on Github</a>, for example by reviewing my repository you can learn about Modal Intercepting Route, Route Grouping to having Multiple RootLayout and Protected Route or Segment and all sub-segments.</p><h4>The App Router</h4><p>In version 13, Next.js introduced a new <a href="https://nextjs.org/docs/app/building-your-application/routing#the-app-router">App Router</a> built on React Server Components, which supports shared layouts, nested routing, loading states, error handling, and more. The App Router works in a new directory named /app.</p><h4>Setup a Next.js project</h4><p>Create a new Next.js project using create-next-app:</p><pre>npx create-next-app@latest my-next-amazing-app</pre><p>After running the above commnad you will get some prompts, We need to use TypeScript and App Router for our project, for the rest of options you choose whatever you would like to use.</p><p>Then install NextAuth dependency:</p><pre>npm i next-auth</pre><h4>Add NextAuth to your API route</h4><p>To add NextAuth to your project create a file named route.ts in the /app/api/auth/[...nextauth]/ address, if this folders do not exist just create it, This file contains the dynamic route handler for NextAuth.js which will also contain all of our global NextAuth.js configurations too.</p><blockquote>Note: All requests to /api/auth/* (signIn, callback, signOut, etc.) will automatically be handled by NextAuth.js.</blockquote><p>In /app/api/auth/[...nextauth]/route.ts route put the below codes:</p><pre>import NextAuth, { NextAuthOptions } from &quot;next-auth&quot;;<br>import GithubProvider from &quot;next-auth/providers/github&quot;;<br>import GoogleProvider from &quot;next-auth/providers/google&quot;;<br><br>export const authOptions: NextAuthOptions = {<br>  // Configure one or more authentication providers<br>  providers: [<br>    GithubProvider({<br>      clientId: process.env.GITHUB_CLIENT_ID as string,<br>      clientSecret: process.env.GITHUB_SECRET_ID as string,<br>    }),<br>    GoogleProvider({<br>      clientId: process.env.GOOGLE_CLIENT_ID as string,<br>      clientSecret: process.env.GOOGLE_SECRET_ID as string,<br>    }),<br>  ],<br>  secret: process.env.NEXTAUTH_SECRET as string,<br>};<br><br>const handler = NextAuth(authOptions);<br><br>export { handler as GET, handler as POST };</pre><p>As you can see I imported just two Github and Google providers, But you may use <a href="https://next-auth.js.org/configuration/providers/oauth#built-in-providers">other build-in OAuth providers that NextAuth support</a>. In our authOptions object I also set the secret value, It’s a secret key string that NextAuth use it for session encryption. Generally in authentication system, after user logged-in to the application we need to create a secure session to maintain user login process, so NextAuth will create a encrypted session by using our secret key securely store session information in the server and a cookie in client-side browser.</p><p>The secret string value should be a long, random and confidential string and you can keep it in your .env file. You can create one by running the following command too:</p><pre>openssl rand -base64 32</pre><p>Now that we create our secret key and keep it in our .env file, NextAuth need another environmental variables named NEXTAUTH_URL to keep our project’s base URL:</p><pre>NEXTAUTH_URL=&quot;http://localhost:3000&quot;</pre><p>It’s a good practice to keep all your third-party secret and public keys and credentials in .env file too.</p><h4>The mistake that I did</h4><p>First time I did not set my secret value in my authOptions object, everything was looking good and my app working but every time I tried to login with Google or Github providers, after giving access to providers, providers site redirected me back to my app, but my session object was null, because NextAuth need the secret value to create and encrypt a secret session, so NextAuth return null as my session every time.</p><h4>How to get Google or Github Credentials</h4><p>For Google, Go to your GCP console, Create a new project or use one of your existing project, then go to <a href="https://console.cloud.google.com/apis/credentials">APIs and Services &gt; Credentials</a>, hit Create Credentials and select OAuth client ID.</p><p>For Github, Go to your <a href="https://github.com/settings/profile">Github profile settings</a> &gt; Developer settings &gt; <a href="https://github.com/settings/developers">OAuth Apps</a> and create new OAuth App.</p><p>Then get your client and secret ID and save them in your .env file.</p><h4>Use authentication session in your server rendered pages</h4><pre>import { getServerSession } from &quot;next-auth/next&quot;;<br>import { authOptions } from &quot;@/app/api/auth/[...nextauth]/route&quot;;<br><br>export default async function Home() {<br><br>  // Get user session token<br>  const session = await getServerSession(authOptions);<br>  // session = null || { user: { name, email, image } }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;My Amazing App&lt;/h2&gt;<br><br>      {session &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;p&gt;Signed in as {session.user &amp;&amp; session.user.name}&lt;/p&gt;<br>          &lt;a href=&quot;/api/auth/signout&quot;&gt;Sign out by link&lt;/a&gt;<br>        &lt;/div&gt;<br>      )}<br><br>      {!session &amp;&amp; (<br>        &lt;p&gt;Not signed in&lt;/p&gt;<br>      )}<br><br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Use authentication session in your client side pages or components</h4><p>To retrieving session data in a client side components or pages you need to add <a href="https://next-auth.js.org/getting-started/client#sessionprovider">NextAuth’s </a><a href="https://next-auth.js.org/getting-started/client#sessionprovider">SessionProvider</a> to your layout, then you can access session data by using useSession() hook in all your client pages. I did another mistake here and used SessionProvider directly in my root layout, and faced <strong>Error: React Context is unavailable in Server Components</strong> as layout.tsx is rendering in server but SessionProvider is a client side, to fix this we can create a client component provider.tsx with use client directive:</p><pre>// provider.tsx<br>&quot;use client&quot;;<br>import {SessionProvider} from &quot;next-auth/react&quot;;<br><br>export function Providers({children}: {children: React.ReactNode}) {<br>  return &lt;SessionProvider&gt;{children}&lt;/SessionProvider&gt;;<br>}</pre><p>Then import it to our layout.tsx and wrap our children with our Providers component:</p><pre>// layout.tsx<br>import {Providers} from &quot;./providers&quot;;<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>          &lt;Providers&gt;{children}&lt;/Providers&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Now we can access session in all our client components or pages:</p><pre>// page.tsx<br>&quot;use client&quot;;<br>import {useSession} from &quot;next-auth/react&quot;;<br><br>export default function Home() {<br>  const {data: session, status} = useSession();<br>  console.log(&quot;status&quot;, status);<br>  console.log(&quot;session&quot;, session);<br><br>  return &lt;div&gt;Client Page&lt;/div&gt;;<br>}</pre><p>Full Source Code on Github: <a href="https://github.com/rezahedi/nextjs-nextauth-starter">https://github.com/rezahedi/nextjs-nextauth-starter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50cb23282c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a contact form in Astro, Vercel and SendGrid]]></title>
            <link>https://medium.com/@rezahedi/how-to-build-a-contact-form-in-astro-vercel-and-sendgrid-b924a76fd739?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b924a76fd739</guid>
            <category><![CDATA[sendgrid]]></category>
            <category><![CDATA[astrojs]]></category>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 17:16:45 GMT</pubDate>
            <atom:updated>2023-04-21T18:13:17.307Z</atom:updated>
            <content:encoded><![CDATA[<p>Having contact form in your website make it easier for users to interact with you and also look more professional, but have downsides, It opens a door for spammer/hackers to give you headache too.</p><h3>Create Astro Project</h3><p>To start building our contact form first we should have our Astro project to be ready:</p><pre>npm create astro@latest<br>npm run dev</pre><p>Now that your Astro project is ready and running locally, create your first page and add the form with necessary input fields. as Astro is a <a href="https://docs.astro.build/en/core-concepts/routing/">file-based routing</a>, by creating new file in src/pages/ you will have new endpoint in your site.</p><p>New file: <em>src/pages/contact.astro</em></p><pre>---<br>// Frontmatter section<br>// Component scripts goes here.<br>---<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Contact Me&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Say Hi to me!&lt;/h1&gt;<br>    &lt;form method=&quot;POST&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Name&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;input type=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Email&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;textarea name=&quot;message&quot; placeholder=&quot;Message&quot;&gt;&lt;/textarea&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Astro uses a code fence (---) to identify the <a href="https://docs.astro.build/en/core-concepts/astro-components/">component script</a> in your Astro component. If you’ve ever written Markdown before, you may already be familiar with a similar concept called <em>frontmatter.</em> Astro’s idea of a component script was directly inspired by this concept.</p><p>Although there are <a href="https://austingil.com/how-to-build-html-forms-right-security/">security aspects to consider when creating forms</a> that I’m not covering here but it’s an important topic to keep in mind.</p><h3>Setup SendGrid</h3><p>SendGrid is a popular email delivery platform that provides a wide range of email marketing and transactional email services. SendGrid is a reliable and flexible email delivery platform that we are going to use it to send emails.</p><p>First, create new <a href="https://signup.sendgrid.com/">SendGrid account</a> or use an existing one, then create your API key <a href="https://app.sendgrid.com/guide/integrate/langs/nodejs">here</a>. The SendGrid’s API keys always start with “SG.”!</p><p>Sendgrid requires you to create a Sender Identity to protect against spam and malicious mails. To do so, go to the <a href="https://app.sendgrid.com/settings/sender_auth">Sendgrid Identity page</a> and click on Create New Sender to create a sender identity.</p><p>You’ll be rqeuired to fill out a detailed form. Just complete the form and hit submit. Finally, just verify your email address and you’re done.</p><p>Once you’ve retrieved the API keys, add it to your .env file in your local environment:</p><pre>SENDGRID_API_KEY= SG.YOUR_API_KEY_HERE</pre><p><em>Note: If you setup </em><em>.gitignore in your project to ignore </em><em>.env files, so do not forget to add your env variable </em><em>SENDGRID_API_KEY under your project in Vercel, Settings &gt; Environment Variables.</em></p><p>Then we need to install SendGrid’s package:</p><pre>npm i --save @sendgrid/mail</pre><h3>Create the Vercel serverless function</h3><p>The SendGrid does not allow browser-based API calls, because of security reasons, also if you do, you will reveal your API key to the public. I did and received a CORS error from SendGrid API, So we should have a server-side function and do our SendGrid API call on server, We need to create a Nodejs function.</p><pre>npx astro add vercel</pre><p>This command will install <em>@astrojs/vercel astro@latest</em> and change your project’s configuration in <em>/astro.config.mjs</em> file by importing vercel serverless, adding <em>output: ‘server’</em> amd <em>vercel()</em> as adapter.</p><pre>import { defineConfig } from &#39;astro/config&#39;;<br><br>import vercel from &quot;@astrojs/vercel/serverless&quot;;<br><br>// https://astro.build/config<br>export default defineConfig({<br>   output: &#39;server&#39;,<br>   adapter: vercel()<br>});</pre><p>Now we can receive data from our contact form on server-side, validate, handling errors and do the SendGrid API call on server. You can read more about <a href="https://vercel.com/docs/frameworks/astro">Server-Side Rendering (SSR) on Vercel documentation</a>.</p><pre>---<br>import sendGrid from &#39;@sendgrid/mail&#39;;<br>sendGrid.setApiKey( import.meta.env.SENDGRID_API_KEY );<br><br>if (Astro.request.method === &#39;POST&#39;) {<br>  try{<br>    // Getting posted data from our contact form<br>    const data = await Astro.request.formData();<br>    const name = data.get(&#39;name&#39;);<br>    const email = data.get(&#39;email&#39;);<br>    const message = data.get(&#39;message&#39;);<br><br>    // TODO: Do not forget to do validation and error handling over received data from your contact form.<br><br>    // Sending email<br>    const msg = {<br>      to: &#39;test@example.com&#39;, // Change to your recipient<br>      from: &#39;text@example.com&#39;, // Change to your verified sender<br>      replyTo: {email:email, name:name},<br>      subject: `Contact form submission from ${name}`,<br>      text: message,<br>    }<br>    await sendGrid.send(msg).then(() =&gt; {<br>      console.log(&#39;Email sent&#39;)<br>    }).catch((error) =&gt; {<br>      console.error(error)<br>    });<br><br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br>---<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Contact Me&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Say Hi to me!&lt;/h1&gt;<br>    &lt;form method=&quot;POST&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Name&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;input type=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Email&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;textarea name=&quot;message&quot; placeholder=&quot;Message&quot;&gt;&lt;/textarea&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>It’s an old-fashion to handle the forms like this by reloading entire page for posting data to servers, but it’s just the base codes, So next step is to make http request (send and receive form’s data) by browser’s fetch API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b924a76fd739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I build SSG site and host it for free on Firebase]]></title>
            <link>https://medium.com/@rezahedi/how-i-build-ssg-site-and-host-it-for-free-on-firebase-d4a8eb0d398b?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a8eb0d398b</guid>
            <category><![CDATA[statis-site-generator]]></category>
            <category><![CDATA[hexojs]]></category>
            <category><![CDATA[firebase-hosting-server]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 16:18:03 GMT</pubDate>
            <atom:updated>2023-03-26T16:18:03.366Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m always amazed by Bamyan, a city in the central highlands of Afghanistan. The people are kind and hardworking, the young generation is curious and energetic, and the city is full of life, color, and history. When my wife got a job in local government in Bamyan, I saw it as an opportunity to use my web development skills to promote this incredible place.</p><p>We decided to gather reliable content and information and create a website to introduce more people to the beauty of Bamyan. Through our website, we hope to showcase the city’s rich culture, history, and people, and to make it more accessible to a wider audience. I was excited to use my skills to help promote Bamyan and share its wonders with the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgcZkFXSVFwoaKcd2MELww.jpeg" /><figcaption><a href="https://visit-bamyan.com/">https://visit-bamyan.com</a></figcaption></figure><p>So I sketched the first-look pages in I<a href="https://www.invisionapp.com/inside-design/freehand-online-whiteboard-for-everyone/">nVision Freehand tool</a>. Freehand is a great digital whiteboard for brainstorming with your team. Then designed the user interface and the prototype in Figma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w7vld68hrYMsqS3J8tfmgA.png" /><figcaption><a href="https://freehandapp.com/">InVision Freehand</a></figcaption></figure><p>Then I decided to go with SSG stacks (Static Site Generator) to learn more about SSGs.</p><p>A static site generator is a software application that creates HTML pages from templates or components and a given content source. Most static site generators, <a href="https://github.com/hexojs/hexo">including HexoJs</a> that I used for my website, accept <a href="https://daringfireball.net/projects/markdown/">Markdown</a>-formatted text files as a source, although SSGs is not limited to Markdown. You can find a list of <a href="https://jamstack.org/generators/">SSGs in JamStack website</a>.</p><p>As SSGs compiling files into static HTML, CSS, and JavaScript, This reduces the risk of security attacks and makes the website more scalable and cost-effective to host. Developers can also use version control systems to manage changes to the code and optimize the website for search engines. SSGs are a great option for websites that require speed, security, scalability, and cost-effectiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcoP0vliTEUSzJJ6s4tLFQ.png" /><figcaption><a href="https://github.com/hexojs/hexo">Hexojs</a></figcaption></figure><p>I choose <a href="https://hexo.io/">Hexo</a> as it’s super fast and simple framework to build a blog platform that I need for my website.</p><pre>$ npm install hexo-cli -g<br>$ hexo init blog<br>$ cd blog<br>$ npm install<br>$ hexo server</pre><p>With above commands your website / blog are ready to open locally. To create a new page or blog post you just need run following command:</p><pre>$ hexo new &quot;Hello Hexo&quot;</pre><p>After customizing all your needs and template and creating your website’s pages, last step is to generate a production version and push it to your hosting server.</p><pre>$ hexo generate</pre><p>Now that you have all your statis site’s files generated, you need to host it somewhere on a server, There are free hostings like Github, Cloudflare, Netlify and Firebase.</p><p>I selected <a href="https://firebase.google.com/">Firebase</a> as my free hosting, Firebase is a Backend-as-a-Service (BaaS) platform provided by Google that offers a variety of services, including cloud storage, authentication, real-time database, hosting, machine learning, analytics, NoSQL, and more. It enables developers to build mobile and web applications quickly without needing to set up and manage server infrastructure. Firebase is well-suited for mobile app development too, with features like real-time database and scalability. Firebase provides a reliable, secure, and scalable infrastructure for running applications, with automatic scaling and security features built in.</p><p>You need to have account in Firebase, I believe you might already have a Gmail account, which is enough, If not create one!</p><p>Login to Firebase and create your project, then install the Firebase CLI, login, and initialize and link your project:</p><pre>&gt; npm i -g firebase-tools<br>&gt; firebase login<br>&gt; firebase init hosting<br>&gt; firebase deploy --only hosting</pre><p>That’s all I did to create and host my website, <a href="https://visit-bamyan.com/">visit-bamyan.com</a>, and all the <a href="https://github.com/rezawm/visit-bamyan.com">visit-bamyan.com codes are available on my Github</a> to review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a8eb0d398b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn React in 10 tweets (with hooks)]]></title>
            <link>https://medium.com/@rezahedi/learn-react-in-10-tweets-with-hooks-2492e0e329db?source=rss-e398bc6bfdb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2492e0e329db</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Reza Zahedi]]></dc:creator>
            <pubDate>Sat, 21 Sep 2019 07:38:45 GMT</pubDate>
            <atom:updated>2019-09-21T07:42:21.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKxD0tTFZRx5wwjyHOZ6Yg.jpeg" /><figcaption>Image from <a href="https://spdload.com/jobs-vacancies/front-end/front-end-developer-react-js/">spdload</a></figcaption></figure><p>I’m learning React, React-Native, Redux and related subjects these days and find these branch of tweets by <a href="https://twitter.com/chrisachard/status/1175022111758442497">Chris Achard</a> useful to me!</p><p>1. How React Works: You display data on a webpage , a user interacts with it, now the data changes and you want the webpage to look different, React does that for you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*hbHVXSVhgaJ4P-gX76F3tg.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022123829616640">https://twitter.com/chrisachard/status/1175022123829616640</a></figcaption></figure><p>2. To think in React: Break your UI into custom components, Each component is responsible for displaying itself, based on the _external_ and _internal_ data available. Build trees of these components for a full UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*cwfMFZwkgB7rQY0vgZ-xQg.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022129781387264">https://twitter.com/chrisachard/status/1175022129781387264</a></figcaption></figure><p>3. Components are functions that return JSX. JSX looks like HTML but is actually JavaScript, Inside of JSX use curly braces to contain JS, A lot of people go “YUCK!” when they see HTML mixed into JS, but JSX is actually one of the things that makes React awesome</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*0xUC3NGchJYx-pKz7zzeXg.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022135800152065">https://twitter.com/chrisachard/status/1175022135800152065</a></figcaption></figure><p>4. After defining a function component, you can use it within another component , It is a “custom component” Use this method to build a “tree” of components that defines your entire UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*TQpn1vhIzkkNh5rYyyFZOw.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022142691381248">https://twitter.com/chrisachard/status/1175022142691381248</a></figcaption></figure><p>5. Data that comes in from the outside of a component is called “props” (properties), This can be passed from a parent to a child through JSX attributes, Props come into function components as the first argument to the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*9JW3XT9ufB5ZtfucieVufw.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022150392197121">https://twitter.com/chrisachard/status/1175022150392197121</a></figcaption></figure><p>6. Internal, _changeable_ data is called “state”. State is defined by the `useState` function, which returns the data, and a function to change that data (in an array). NEVER set the state variable directly , Always use that function (because of the next point)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*THJGzFdT2hTimH1UDbnF9w.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022156964667394">https://twitter.com/chrisachard/status/1175022156964667394</a></figcaption></figure><p>7. When state or props change, your component updates AUTOMATICALLY, This is the magic of React! You almost _never_ have to go into the DOM yourself (If you think that you do, you’re probably trying to do it the “hard way”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ruYPjG0MwGp5CfA9lCG2pQ.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022165034446848">https://twitter.com/chrisachard/status/1175022165034446848</a></figcaption></figure><p>8. Make lists of things by looping over an array of data with `map`, Return an element from each loop iteration, Provide a unique `key` to each element in the list to ensure best performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*0d3rrTODG2BrdCYCMscUYw.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022172751970305">https://twitter.com/chrisachard/status/1175022172751970305</a></figcaption></figure><p>9. Two built-in ways to style components, First set the class with `className`, and use regular CSS files, Second way set inline styles with `style={{ }}` and camel cased keys. Notice the double curly braces</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*MSl-8Bv4zy0bFW9KNyIWLg.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022181300023296">https://twitter.com/chrisachard/status/1175022181300023296</a></figcaption></figure><p>10. Perform Async functions and side effects inside of `useEffect` (takes a callback) The second argument is an array of dependencies. Include any variable the useEffect uses that might change, or an empty array if there are none.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*tMgNXP47F3jHX5xkv6TCbg.jpeg" /><figcaption><a href="https://twitter.com/chrisachard/status/1175022188518416386">https://twitter.com/chrisachard/status/1175022188518416386</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2492e0e329db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>