teleren/devto huggingface dataset:
Generate Metadata Dynamically for multiple Pages in Next.js (App Router)
Tags: nextjs, javascript, webdev
Published: 2024-04-14 12:15:00

I was working on my side project and wanted to generate metadata dynamically for multiple static pages in Next.js. Here’s how I did it. I don’t know if this is the best way to do it, but it works for me. And this used DRY (Don’t Repeat Yourself) principle so it’s good.

I had a list of pages that I wanted to generate metadata for. I wanted to generate metadata for those pages dynamically. I didn’t want to repeat the same code for each page. Because in the future I might add more pages and I don’t want to repeat the same code again and again. So I created a function that takes the page name and returns the metadata for that page.

Here’s how I did it.

Code
```tsx
// pageList.ts

export const pageList = [
  {
    title: "Page 1",
    description: "This is the page 1",
    slug: "page-1",
    image: "page-1.png",
  },
  {
    title: "Page 2",
    description: "This is the page 2",
    slug: "page-2",
    image: "page-2.png",
  },
  {
    title: "Page 3",
    description: "This is the page 3",
    slug: "page-3",
    image: "page-3.png",
  },
];
```

This is the list of pages that I want to generate metadata for. I have the title, description, slug, and image for each page.

```ts
// utils.ts

import { pageList } from "./pageList";

export const generateMetaData = (pageSlug: string) => {
  const page = pageList.find((page) => page.slug === pageSlug);
  if (!page) {
    return {
      title: "404",
      description: "Page not found",
      openGraph: {
        title: "404",
        description: "Page not found",
        url: "/404",
        images: [
          {
            url: "https://example.com/image.jpg",
          },
        ],
      },
    };
  }
  return {
    title: page.name,
    description: page.description,
    openGraph: {
      title: page.name,
      description: page.description,
      url: `/${page.slug}`,
      images: [
        {
          url: page.image || "https://example.com/image.jpg",
        },
      ],
    },
  };
};
```

This is the function that generates metadata for the page. It takes the page slug as an argument and returns the metadata for that page. If the page is not found in the list of pages, it returns the metadata for the 404 page.

Now I have the function that generates metadata for the page. I can use this function every page to generate metadata for that page.

```tsx
// page-1/page.tsx

import { generateMetaData } from "./utils";
import type { Metadata } from "next";

export const metadata: Metadata = generateMetaData("page-1");

export default function Page() {
  return <div>your stuff here</div>;
}
```

This is how I generate metadata for the page. I import the generateMetaData function and call it with the page slug. I use the metadata object to set the metadata for the page.

Please let me know if there is a better way to do this. I would love to hear your thoughts. As I’m learning Next.js, I’m sure there are better ways to do this. But this works for me. I hope this helps you too. This all things just for the sake of SEO.
Securing Next.js Applications with Robust CSP Headers
Tags: nextjs, webdev
Published: 2024-04-14 11:45:24

Keeping your web applications safe is crucial, especially when using frameworks like Next.js that build dynamic sites. One important way to boost security is by setting up Content Security Policy (CSP) headers. In this blog post, I’ll walk you through how to add CSP headers in Next.js, focusing on version 14.2, but this guide should be useful for anyone using Next.js 13 or newer.

### **Why CSP is Important**

CSP headers protect your app from certain types of attacks, like cross-site scripting (XSS) and unwanted data injection. By specifying which sources your app can trust, CSP prevents harmful scripts from running, making your site safer.

## **Generic Approach and Its Limitations**

Typically, you might find online guides suggesting you to simply modify your **`next.config.js`** file to add CSP headers. While this approach can work for adding general headers, it often falls short when dealing with more complex configurations or specific security requirements.

## **Follow the Official Documentation**

It's best to follow the official Next.js documentation for the most reliable instructions:

[Next.js CSP Documentation](https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy#why-use-a-nonce)

However, even the official guide has some gaps, which you might discover the hard way through trial and error. That's what leads many developers to seek out additional resources like this blog.

## **Addressing the Gaps**

If you've followed the documentation, you might find everything works perfectly in your local development environment. But as soon as you build and run your application, you encounter errors related to script handling, which are often not nonce-compliant.

This issue arises because, by default, Next.js does server-side rendering (SSR), and during the build and run phase, the nonces for scripts generated by Webpack aren't set correctly.

### **The Solution**

Currently, the best solution is to include the following line in your root layout:

```jsx
export const dynamic = 'force-dynamic';
```

This directive opts the component out of static optimization, which can interfere with nonce propagation and CSP enforcement during the build process.

### **Final Steps**

Make sure that your root layout is configured as a server component, not a client component. This is crucial because server components handle headers and optimizations differently, affecting your security settings directly.

### **Conclusion**

Implementing robust CSP headers in Next.js requires more than just adding a few lines of code to your configuration. Understanding the nuances of nonce management and how Next.js handles scripts and styles at build time can save you from security headaches. By following the steps outlined above, you can ensure that your application not only runs smoothly but also maintains high security standards.
Coding Training: How to Improve Your Coding Skills
Tags: coding, programming, leetcode
Published: 2024-04-14 11:37:22

There's a lot that goes into becoming a better programmer, so let's just tackle one way that helps improve your programming skills today: practice, practice, _practice_ solving problems.  😤

## Practice Makes Perfect

Mastering any skill takes time, and coding is no different.  To help you get started, I've listed some of my favorite websites below that offer fun and engaging ways to practice your coding skills.

Remember that the more you code, the better you'll become!  🚀🚀

_Note: One way that can help is to try setting aside specific times in your day to write code.  Morning and evening are my personal favorites, but it's different for everyone.  Whatever you choose, though, consistency is key!_

## CodinGame

[CodinGame](https://www.codingame.com) is probably my top recommended site for someone looking for a place to improve their programming skills.  This platform delivers coding practice through a variety of games, challenges, and contests.  It's a fun way to learn and easy to get started with, but also contains more demanding challenges for advanced coders further along in their careers.

## Codewars

[Codewars](https://www.codewars.com) is another online site geared towards programming practice.  This platform centers around the concept of "kata," which are small, focused coding exercises. These kata target specific techniques and problem-solving approaches in various programming languages.

Codewars doesn't have games like CodinGame, but they do incorporate gamification techniques to make learning more engaging. As you solve different exercises, you can progress through ranks and earn points (honor) for completing katas and contributing to the community. You can even create your own challenges!

## Leetcode

[Leetcode](https://leetcode.com), infamous among computer science students, is a popular online platform designed to help programmers prepare for technical coding interviews.  (It's also, unofficially, known for causing many tears during junior and senior CS years. 🥲)

Leetcode includes guides on different areas of programming, as well as targeted practice.  Their problems challenge users on specific algorithms, data structures, and efficient problem-solving techniques.

## Exercism

[Exercism](https://exercism.org) is an awesome online platform for beginner to intermediate-level coders to practice their skills, focusing on a specific programming language.  Experienced programmers can also volunteer to mentor beginners and provide feedback on their code.  This platform is completely free and open source, so anyone can contribute to the exercises and create new ones for different languages!

## Conclusion

I hope this list helps you find tools that can help you improve your skills!  There are a lot of other great websites out there - are there any you enjoy using that I haven't mentioned in this short list?  Drop a message in the comments below!

Happy coding!

Catherine
Here is my new workflow with LottieLab to create lottie animations in Flutter
Published: 2024-04-14 11:29:00


I've been building a lot of Lottie animations for my Flutter projects lately, and dealing with Adobe AE for quick edits was a real pain.

Between plugin errors and the whole learning curve, it just slowed me down. Also, collaborating with designers on animation changes felt clunky, with version control issues and files getting passed around.

I came across [LottieLab](https://www.lottielab.com/), and this has pretty much helped me with a better workflow. Here's my workflow now:

- I usually start with design on figma. (or ask my designer to get it done for me)

- Import it to Lottielab's editor

- Animate using the assets. Invite my team, make iterations

- Once we're happy with the animation, export as the lottie file and add it to the project
Flutter Elegant Notification
Tags: flutter, dart, package, opensource
Published: 2024-04-14 11:09:32

**Level Up Your App's Notifications:
A Guide (from the owner himself 🤯) to elegant_notification**

In today's competitive mobile landscape, every detail matters, and that includes how you communicate with your users. Enter `elegant_notification`, a powerful Flutter package that injects a touch of class into your app's notification system.

This article dives deep into `elegant_notification`, exploring its core features, exciting new additions, and how to seamlessly integrate it into your Flutter project. 

### Core Features that Make Your Notifications Shine

* **Built-in Themes:**  Out of the box, `elegant_notification` provides pre-designed themes for success, error, and info messages.

* **Customization:**  Don't like the pre-built themes? `elegant_notification` empowers you to fully customize the look and feel of your notifications. From background colors and animation styles to notification position and even adding a progress bar, the possibilities are endless. 

* **Animations:** Make your notifications stand out with a variety of animation options.

* **Action Stations!** Engage your users by adding clickable buttons or widgets to your notifications.

* **Stacked notifications** The package offer the possiblity to display notifications in stacked way.

### Latest version updates

What elegant notification brings to you with the latest 2.1.1 version:

**Customizable borders style (color, radius, stroke...)**
**Customizable notification shadow**


### Step-by-Step Guide

Here's a quick guide to get you started:
1. **Add the package to your pubspec.yaml:**

``` yaml
dependencies:
  elegant_notification: ^latest_version  # Replace with the latest version number
```

2. **Import the package in your Dart file:**

``` dart
import 'package:elegant_notification/elegant_notification.dart';
```

**Display a notification with ease:**

``` dart
ElegantNotification.success(
  title: Text('Success!'),
  description: Text('Your data has been updated'),
  animation: AnimationType.fromTop,
)
.show(context);
```


3. **Custom notification with stacked options:**

``` dart
ElegantNotification(
  title: Text('Success!'),
  description: Text('Your data has been updated'),
  animation: AnimationType.fromTop,
  stackedOptions: StackedOptions(
    key: 'top',
    type: StackedType.same,
    itemOffset: Offset(-5, -5),
  ),
  border: Border(
    bottom: BorderSide(
    color: Colors.green,
    width: 2,
  ),
 ),
 icon: Icon(
   Icons.access_alarm,
   color: Colors.orange,
 ),
 progressIndicatorColor: Colors.orange,
 background: Colors.white,
)
.show(context);
```

You can imagine what you can do with all this customizations and other attributes (I'll let you unleash your creativity with it)

Head to [https://pub.dev/packages/elegant_notification](https://pub.dev/packages/elegant_notification) for more in-depth documentation about this package and let me know if you have any questions, issues or suggestions
HOW TO CREATE A LINUX VM AND CONNECT TO IT USING PASSWORD AUTHENTICATION
Published: 2024-04-14 11:05:42

Creating a Linux virtual machine (VM) on Microsoft Azure and connecting to it using password authentication involves several steps. Here's a basic guide to get you started:

**Sign in to the Azure Portal:** Go to https://portal.azure.com and sign in with your Azure account.

**Create a Virtual Machine:**
a)	Click on "Create a resource" in the upper-left corner.
b)	Search for "Virtual machine" and click on it.
c)	Click on "Create" to start the VM creation process.

**Basics:**
a)	Choose your subscription.
b)	Create a new resource group or select an existing one.
c)	Enter the virtual machine name.
d)	Choose a region.
e)	Select the desired OS image (choose a Linux distribution).


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6m3lxb7tjygq7tunk33.png)

**Size:** Choose the size of the VM according to your requirements. You can start with a basic size and scale up as needed.

**Settings:**
a)	Choose a username for the administrator account.
b)	Select "Password" under Authentication type.
c)	Enter and confirm the password for the administrator account.

**Public Inbound Ports:** Open port 22 (SSH) to allow remote access to the VM.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8f27z9amdemjbbe7uxeu.png)

**Review + Create:** Review your VM configuration and click on "Create" to start provisioning the VM.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcjg0f6svs7d3zwy7gd6.png)

**Wait for Deployment:** Azure will now deploy the VM. This process may take a few minutes.

**Access the VM:**
a)	Once the VM is deployed, you can access it using SSH.
b)	Use an SSH client such as PowerShell (on Windows) or Terminal (on macOS/Linux) to connect to your VM.
c)	Enter the public IP address or DNS name of your VM, along with the username and password you provided during setup.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0k4u0ii1csby3kysvz7.png)

d)	Replace username with your administrator username and public_ip_address with the public IP address of your VM.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mw2n3ss3q01r3d1heo49.png)

That's it! You should now be connected to your Linux VM on Azure using password authentication. 
Remember to follow best practices for security, such as regularly updating your VM, using strong passwords, and implementing additional security measures as needed.
Di1 - AI Driven Insights With Cloudflare
Tags: cloudflarechallenge, devchallenge, ai, nextjs
Published: 2024-04-14 10:35:10

*This is a submission for the [Cloudflare AI Challenge](https://dev.to/devteam/join-us-for-the-cloudflare-ai-challenge-3000-in-prizes-5f99).*

## What I Built

Di1 is an AI-powered T2SQL Chatbot for Cloudflare D1. It allows users to interact with the Y Combinator dataset using natural language queries, can be customized to any data that is stored in Cloudlfare D1. Users can ask questions about the dataset, and Di1 will generate the corresponding SQL queries and produce charts and graphs, to retrieve the relevant information from the Cloudflare D1 database. The chatbot provides an intuitive and user-friendly interface for exploring the dataset without requiring knowledge of SQL syntax.


![Screenshot of the website Di1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/63o8dh26gpzmovmhnjvy.png)

## Demo

Deployed app - https://di1-iyr.pages.dev/

Generated example chat - https://di1-iyr.pages.dev/chat/NQFtTkt


## My Code

The source code for Di1 is available on GitHub: https://github.com/kaarthik108/di1

## Journey

Just went all out on **cloudflare** product offerings. 
The project is built with the following stack:

- **Cloudflare Workers AI** - Embedding model
- **Cloudflare Vectorize** - Store vectors for RAG
- **Cloudflare AI Gateway** - Caching LLM query and ratelimiting
- **Cloudflare Pages** - Hosting Nextjs
- **Cloudflare Python Workers** - For importing CSV data to D1
- **Cloudflare D1** - For context query with RAG, and also to store chat responses.
- **OpenAI** - GPT4-turbo for function calling

Building Di1 was a valuable learning experience within a short timeframe. 
The design process was rewarding, and the integration of multiple Cloudflare products resulted in a comprehensive solution.

Achieving high accuracy with function calling using the Workers AI model `@hf/nousresearch/hermes-2-pro-mistral-7b` proved challenging compared to `GPT-4`. As the app relies heavily on function calling capabilities, this is an area for future exploration as Cloudflare expands its model offerings.



**Multiple Models and/or Triple Task Types**


The app currently uses two LLM's 
Workers AI - Embedding model `@cf/baai/bge-large-en-v1.5`
OpenAI - Chat model for function calling `GPT4-Turbo`


Team Submissions: https://dev.to/kaarthik108
Tips: The power of "cd -" command
Tags: linux, tutorial, terminal
Published: 2024-04-14 10:29:28

I'm often posting advanced tips, today I will talk about something very simple, but that I noticed even experienced terminal users are not aware of: the `cd -` command.

# Quick intro about `cd`

The `cd` command, short for "change directory" is used in both Windows Command Prompt and Linux terminals to navigate through the file system.

The following command will
bring you to a folder `/var/log`

```console
~$ cd /var/log
```

This is basic, OK.

# Navigation

Let's go further.

```console
~$ cd src/foo/bar
src/foo/bar$ #do something, but you have to move to another folder
src/foo/bar$ cd /var/log
/var/log$ # do something, but you have to move back to src/foo/bar
/var/log$ cd ~/src/foo/bar
src/foo/bar: $ # do something, but you have to move to log folder
src/foo/bar$ cd /var/log
/var/log$ # whatever
```

OK these are basic moves.

You all know `cd ..`, `cd ~`, or `cd`, but do you know about `cd -` ?

# `cd -` command

`cd -` will bring you back to previous folder.

Let's try the same navigation example

```console
~$ cd src/foo/bar
src/foo/bar$ #do something, but you have to move to another folder
src/foo/bar$ cd /var/log
/var/log$ #do something, but you have to move back to src/foo/bar, we could use cd ~/src/foo/bar, but let's try cd -
/var/log$ cd -
src/foo/bar$ #do something, but you have to move to log folder, cd - will bring you back to 
src/foo/bar$ cd -
/var/log$ # whatever
```

This something I'm using multiple times a day
EyeControl
Published: 2024-04-14 10:22:58

**_Idea_**:
- I wonder whether the code can track the place on the screen user is lookin on. To know the borders, the user would be firstly asked to highligth the borders of the screen with the glance. 
- As the program will track the direction of the glance of the user, knowing the borders of the screen, it whould draw the interface where the user looks better - and vice versa.
- It may be helpful for gamedev, where the recources to graph the picture are limited - it whould make games high graphic more accessible.

**_Questiosn_**:
1. Mabe you know some examples of projeccts that done similar things
2. If you got interested in that idea and may help t ocode it - I would be extremely happy to cowork with you
Nước hoa chiết 10ml Yupi Perfume
Tags: yupiperfume, nuochoachietchinhhang
Published: 2024-04-14 09:32:00

Yupi Perfume chỉ bán nước hoa chiết chính hãng (Authentic) ⭐ Đảm bảo /m/0p833 chiết nguồn gốc rõ ràng ⭐ Cam kết chất lượng nước hoa chiết 10ml
#yupiperfume #yupivn #nuochoachietchinhhang #nuochoachiet #nuochoachiet10ml
Thông tin liên hệ Yupi Perfume:
Địa chỉ:  102 Lê Tuấn Mậu, Phường 13, Quận 6, TPHCM
Hotline: 0911.17.03.96
Email: yupiperfume@gmail.com
Website: [](https://yupi.vn/collections/nuoc-hoa-chiet)
[](https://vi.wikipedia.org/wiki/N%C6%B0%E1%BB%9Bc_hoa)
Kết nối mạng xã hội với @yupiperfume:
[](https://dzone.com/users/5015940/nuochoachietyupi.html)
[](https://www.dmca.com/Accounts/default.aspx?ID=7354d3e3-22d1-455c-8dc0-a527f395b0d0)
[](https://jsfiddle.net/nuochoachietyupi/Lhsq8t12/)
[](https://heylink.me/nuochoachietyupi/)
[](https://my.link.gallery/nuochoachietyupi)
[](https://roosterteeth.com/g/user/nuochoachietyupi/activity``)
Laravel storage paths and advantages. Simplified explanation
Tags: laravel
Published: 2024-04-14 09:26:00

Probably you have heard about Laravel storage paths. They are a great way to manage files. Here is a simplified explanation about them.

you may have noticed there is two folders in Laravel root folder. One is **public** and other is **storage**. Let us see the difference first. 

Let us store the same file inside both folders. We saved "test.webp" file inside both **public** and **storage** folders.

Now the image stored inside public folder can be accessed easily from browser like this

```
http://localhost:8000/test.webp
```

But we can't access the file stored in `storage/test.webp` from browser like this. But we can access that file like this,

Inside `routes\web.php`

```
Route::get('storagepath/{filename}', function ($filename) {
    $path = storage_path($filename);

    return response()->file($path);
});
```

And it can be accessed from browser like this,

```
http://localhost:8000/storagepath/test.webp
```

Now the important think to understand is there is no actual path called **storagepath** in root. It is created in runtime. Advantage here is you can restrict access to files from this routes,

```
Route::get('storagepath/{filename}', function ($filename) {

    // Construct the full path to the file
    if ($filename == 'test.webp') {
        $path = storage_path($filename);

        // Check if the file exists
        if (!file_exists($path)) {
            // If the file does not exist, return a 404 Not Found error
            abort(404);
        }

        return response()->file($path);
    }

    // Deny access to 'test2.webp' or any other file
    abort(403, 'Unauthorized access.');
});
```

Now imagine we have a file stored inside `storage\test2.webp` directory. The file will not be able to access from route like this


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdgysfqx2xiotumd3g2t.png)

This way we can restrict logged in users from accessing other peoples images or files. Or can add any other restriction.

###Public access for storage files.

There is a way to open some part of **storage** folder to public.

```
php artisan storage:link
```

This code will create a symlink from storage folder to public folder. Symlink is a short cut. Check here, 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyvqzs85n0bf3zfouw6e.png)

This has created a short cut from **public** to **storage\app\public** folder. After creating a symlink, You can access this file **storage\app\public\test.webp** from browser in this route,

```
http://localhost:8000/storage/test.webp
```