Duong Tran

Duong Tran

1660891501

Cách lấy dữ liệu động trong ứng dụng Next.js với các tuyến API

Hướng dẫn này cho biết cách sử dụng API bộ định tuyến của Next.js để lấy dữ liệu động trong các ứng dụng của bạn. Nhận dữ liệu trong ứng dụng yêu cầu xác thực hoặc ủy quyền với Next.js.

Dữ liệu là một trong những thứ quan trọng nhất tạo nên một ứng dụng web hoặc một ứng dụng gốc thông thường. Chúng ta cần dữ liệu để có thể nhìn thấy và có lẽ hiểu được mục đích của một ứng dụng. Trong bài viết này, chúng ta sẽ xem xét một cách tiếp cận khác để lấy dữ liệu trong một ứng dụng yêu cầu xác thực hoặc ủy quyền bằng Next.js.

Next.js có năm loại mẫu tìm nạp dữ liệu để xác định cách bạn muốn nội dung được nhìn thấy trong ứng dụng của mình: tạo trang web tĩnh (SSG), hiển thị phía máy chủ (SSR), hiển thị phía máy khách (CSR), tĩnh gia tăng tái tạo (ISR) và định tuyến động.

Bạn có thể chọn bất kỳ mẫu nào trong số các mẫu này phù hợp với cấu trúc ứng dụng của mình. Để tìm hiểu thêm về các mẫu này, hãy đọc về chúng trong tài liệu chính thức .

Bài viết này tập trung vào việc tạo trang web tĩnh và định tuyến động. Việc sử dụng các mẫu này yêu cầu sử dụng các phương pháp tìm nạp dữ liệu getStaticPropsvà . getStaticPathsCác phương pháp này đóng vai trò duy nhất trong việc thu thập dữ liệu.

Chúng ta đã nói về dữ liệu động trong một thời gian. Hãy hiểu điều đó thực sự có nghĩa là gì.

Giả sử chúng tôi có danh sách người dùng trong một ứng dụng đang được hiển thị trên trang web và chúng tôi muốn nhận thông tin duy nhất cho người dùng khi chúng tôi nhấp vào tên của họ - thông tin chúng tôi nhận được sẽ thay đổi theo hành động chúng tôi thực hiện (nhấp vào tên người dùng).

Chúng tôi muốn một cách hiển thị dữ liệu đó trên một trang (hoặc màn hình) duy nhất trong ứng dụng và getStaticPathsphương pháp tìm nạp dữ liệu cho phép chúng tôi lấy dữ liệu duy nhất cho người dùng. Điều này thường phổ biến trong một mảng các đối tượng người dùng với một khóa ( idhoặc _id) duy nhất, tùy thuộc vào cách đối tượng phản hồi được cấu trúc.

export async function getStaticPaths() {
  return {
    paths: {
      [{
        params: {
          uniqueId: id.toString()
        }
      }],
      fallback: false
    }
  }
}

Khóa duy nhất thu được từ getStaticPathsphương thức (thường được gọi là tham số, viết tắt là params) được truyền dưới dạng đối số thông qua contexttham số trong getStaticProps.

Điều này đưa chúng ta trở lại thực tế là getStaticPathskhông thể làm việc mà không có getStaticProps. Cả hai đều hoạt động cùng nhau, bởi vì bạn sẽ cần chuyển giá trị duy nhất idtừ ​​đường dẫn được tạo tĩnh làm đối số cho contexttham số trong getStaticProps. Đoạn mã dưới đây minh họa điều này:

export async function getStaticProps(context) {
  return {
    props: {
      userData: data,
    },
  }
}

Nhược điểm của việc sử dụng các phương pháp tìm nạp dữ liệu gốc của Next.Js 

Bây giờ chúng ta đã hiểu một chút về tìm nạp dữ liệu động trong Next.js, hãy xem xét nhược điểm của việc sử dụng hai phương pháp tìm nạp dữ liệu nói trên.

Lấy dữ liệu từ một API công khai không yêu cầu ủy quyền với một số loại khóa API trong quá trình tìm nạp dữ liệu có thể được thực hiện với getStaticPropsgetStaticPaths.

Hãy xem cả hai trong số chúng dưới đây:

// getStaticPaths
export async function getStaticPaths() {
  const response = fetch("https://jsonplaceholder.typicode.com/users")
  const userData = await response.json()

 // Getting the unique key of the user from the response
 // with the map method of JavaScript.
  const uniqueId = userData.map((data) => {
    return data.id
  })

  return {
    paths: {
      [{
        params: {
          uniqueId: uniqueId.toString()
        }
      }],
      fallback: false
    }
  }
}

Bạn sẽ nhận thấy rằng giá trị duy nhất idnhận được từ mapphương thức JavaScript và chúng tôi sẽ gán nó dưới dạng giá trị thông qua contexttham số của getStaticProps.

export async function getStaticProps(context) {
  // Obtain the user’s unique ID.
  const userId = context.params.uniqueId

  // Append the ID as a parameter to the API endpoint.
  const response = fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
  const userData = await response.json()
  return {
    props: {
      userData,
    },
  }
}

Trong đoạn mã trên, bạn sẽ thấy rằng một biến có tên userIdđã được khởi tạo và giá trị của nó được nhận từ contexttham số.

Giá trị đó sau đó được thêm vào làm tham số cho URL cơ sở của API.

Lưu ý: Chỉ có thể xuất các phương thức getStaticPropsvà phương thức tìm nạp dữ liệu từ một tệp trong thư mục Next.js.getStaticPathspages

Điều đó làm được khá nhiều điều đó đối với một API công khai. Nhưng khi bạn đang xây dựng một ứng dụng yêu cầu người dùng đăng nhập, đăng xuất và có thể thực hiện một số tìm nạp dữ liệu trong ứng dụng khi họ đăng nhập bằng tài khoản của mình, luồng ứng dụng sẽ khác.

Tìm nạp dữ liệu trong hệ thống đã xác thực. 

Quy trình lấy dữ liệu trong một hệ thống đã xác thực hoàn toàn khác với cách thông thường mà chúng tôi lấy dữ liệu từ API công khai.

Hình dung tình huống này: Một người dùng đăng nhập vào một ứng dụng web và sau đó truy cập hồ sơ của họ. Trên trang hồ sơ của họ (khi nó được hiển thị), họ có thể xem và thay đổi thông tin mà họ đã cung cấp khi đăng ký.

Để điều này xảy ra, phải có một số loại xác minh dữ liệu đang được gửi đến người dùng bởi nhà phát triển đã xây dựng giao diện. May mắn thay, có một mẫu phổ biến để cấp quyền cho người dùng khi họ đăng nhập vào hệ thống: Mã thông báo web JSON (JWT).

Khi người dùng đăng ký sử dụng ứng dụng của bạn lần đầu tiên, thông tin chi tiết của họ được lưu trữ trong cơ sở dữ liệu và JWT duy nhất được chỉ định cho lược đồ của người dùng đó (tùy thuộc vào cách thiết kế API back-end).

Khi người dùng cố gắng đăng nhập vào ứng dụng của bạn và thông tin đăng nhập của họ khớp với những gì họ đã đăng ký ban đầu, điều tiếp theo mà các kỹ sư front-end chúng tôi phải làm là cung cấp trạng thái xác thực cho người dùng để chúng tôi có thể có được các chi tiết cần thiết, một trong số đó là JWT.

Có nhiều trường phái suy nghĩ khác nhau về cách bảo vệ người dùng auth-state, bao gồm sử dụng Redux, Composition trong React và API ngữ cảnh của React (tôi khuyên bạn nên sử dụng API ngữ cảnh). Bài báo của Átila Fassina đề cập đến các mô hình quản lý nhà nước trong Next.js.

Cách tiếp cận phổ biến là lưu trữ JWT localStorage- ít nhất là để bắt đầu, nếu chúng tôi đang xem xét vấn đề bảo mật một cách nghiêm ngặt. Nên lưu trữ JWT của bạn trong một httpOnlycookie để ngăn chặn các cuộc tấn công bảo mật như giả mạo yêu cầu trên nhiều trang web (CSRF) và tập lệnh giữa các trang web (XSS).

Một lần nữa, cách tiếp cận này chỉ có thể thực hiện được nếu phần mềm trung gian cookie thích hợp được cung cấp trong API mà các kỹ sư back-end đã xây dựng.

Nếu bạn không muốn phải tìm hiểu cách các kỹ sư back-end đã thiết kế API, thì một cách thay thế để xác thực trong Next.js là sử dụng dự án xác thực nguồn mở NextAuth.js.

Khi mã thông báo ở localStoragephía máy khách, các lệnh gọi API yêu cầu mã thông báo người dùng làm phương tiện ủy quyền có thể được thực hiện mà không gặp lỗi 501 (trái phép).

headers: {
  "x-auth-token": localStorage.getItem("token")
}

Tìm nạp dữ liệu bằng useRoutermóc 

Trong phần đầu tiên, chúng ta đã biết quá trình tìm nạp dữ liệu động hoạt động như thế nào trong Next.js đối với một ứng dụng không yêu cầu xác thực.

Trong phần này, chúng ta sẽ xem xét cách bỏ qua vấn đề của các phương thức tìm nạp dữ liệu getStaticPropsgetStaticPathsném dấu referenceError(“ localStoragelà không xác định”) khi chúng tôi cố gắng lấy mã thông báo của người dùng localStorage.

Lỗi này xảy ra do hai phương pháp tìm nạp dữ liệu luôn chạy trên máy chủ ở chế độ nền, do đó làm cho localStorageđối tượng không khả dụng với chúng, vì nó ở phía máy khách (trong trình duyệt).

API bộ định tuyến của Next.js tạo ra nhiều khả năng khi chúng tôi xử lý các tuyến và dữ liệu động. Với useRouterhook, chúng ta có thể lấy dữ liệu duy nhất cho người dùng dựa trên ID duy nhất của họ.

Hãy xem đoạn mã dưới đây để bắt đầu:

// pages/index.js

import React from "react";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import Link from "next/link";

const Users = () => {
  const [data, setData] = React.useState([])
  const [loading, setLoading] = React.useState(false)

  const getAllUsers = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: userEndpoints.getUsers,
        headers: {
          "x-auth-token": localStorage.getItem("token"),
          "Content-Type": "application/json",
        },
      });
      const { data } = response.data;
      setData(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  return (
    <React.Fragment>
      <p>Users list</p>
      {data.map((user) => {
          return (
            <Link href={`/${user._id}`} key={user._id}>
              <div className="user">
                <p className="fullname">{user.name}</p>
                <p className="position">{user.role}</p>
              </div>  
            </Link>
          );
        })}
    </React.Fragment>
  );
};

export default Users;

Trong đoạn mã trên, chúng tôi đã sử dụng useEffecthook để lấy dữ liệu khi trang được hiển thị lần đầu tiên. Bạn cũng sẽ nhận thấy rằng JWT được gán cho x-auth-tokenkhóa trong tiêu đề yêu cầu.

Khi chúng tôi nhấp vào một người dùng, Linkthành phần sẽ chuyển chúng tôi đến một trang mới dựa trên ID duy nhất của người dùng. Khi chúng tôi ở trên trang đó, chúng tôi muốn hiển thị thông tin dành riêng cho người dùng đó với id.

Cái useRoutermóc cung cấp cho chúng tôi quyền truy cập vào pathnametrong tab URL của trình duyệt. Với điều đó tại chỗ, chúng tôi có thể nhận được tham số truy vấn của tuyến đường duy nhất đó, là id.

Đoạn mã dưới đây minh họa toàn bộ quá trình:

// [id].js

import React from "react";
import Head from "next/head";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import { useRouter } from "next/router";

const UniqueUser = () => {
  const [user, setUser] = React.useState({
    fullName: "",
    email: "",
    role: "",
  });
  const [loading, setLoading] = React.useState(false);
  const { query } = useRouter();

  // Obtaining the user’s unique ID with Next.js'
  // useRouter hook.
  const currentUserId = query.id;

  const getUniqueUser = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: `${userEndpoints.getUsers}/${currentUserId}`,
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": localStorage.getItem("token"),
        },
      });
      const { data } = response.data;
      setUser(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  React.useEffect(() => {
    getUniqueUser();
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>
          {`${user.fullName}'s Profile | "Profile" `}
        </title>
      </Head>
        <div>
          <div className="user-info">
            <div className="user-details">
              <p className="fullname">{user.fullName}</p>
              <p className="role">{user.role}</p>
              <p className="email">{user.email}</p>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};
export default UniqueUser;

Trong đoạn mã trên, bạn sẽ thấy rằng chúng tôi đã hủy đối tượng truy vấn khỏi useRouterhook, đối tượng mà chúng tôi sẽ sử dụng để lấy ID duy nhất của người dùng và chuyển nó làm đối số cho điểm cuối API.

const {query} = useRouter()
const userId = query.id

Khi ID duy nhất được thêm vào điểm cuối API, dữ liệu dành cho người dùng đó sẽ được hiển thị sau khi trang được tải.

Sự kết luận 

Tìm nạp dữ liệu trong Next.js có thể trở nên phức tạp nếu bạn không hiểu đầy đủ về trường hợp sử dụng của ứng dụng của mình.

Tôi hy vọng bài viết này đã giúp bạn hiểu cách sử dụng API bộ định tuyến của Next.js để lấy dữ liệu động trong các ứng dụng của bạn.

Nguồn bài viết gốc tại https://www.smashingmagazine.com

#nextjs #api #database

What is GEEK

Buddha Community

Cách lấy dữ liệu động trong ứng dụng Next.js với các tuyến API
Duong Tran

Duong Tran

1660891501

Cách lấy dữ liệu động trong ứng dụng Next.js với các tuyến API

Hướng dẫn này cho biết cách sử dụng API bộ định tuyến của Next.js để lấy dữ liệu động trong các ứng dụng của bạn. Nhận dữ liệu trong ứng dụng yêu cầu xác thực hoặc ủy quyền với Next.js.

Dữ liệu là một trong những thứ quan trọng nhất tạo nên một ứng dụng web hoặc một ứng dụng gốc thông thường. Chúng ta cần dữ liệu để có thể nhìn thấy và có lẽ hiểu được mục đích của một ứng dụng. Trong bài viết này, chúng ta sẽ xem xét một cách tiếp cận khác để lấy dữ liệu trong một ứng dụng yêu cầu xác thực hoặc ủy quyền bằng Next.js.

Next.js có năm loại mẫu tìm nạp dữ liệu để xác định cách bạn muốn nội dung được nhìn thấy trong ứng dụng của mình: tạo trang web tĩnh (SSG), hiển thị phía máy chủ (SSR), hiển thị phía máy khách (CSR), tĩnh gia tăng tái tạo (ISR) và định tuyến động.

Bạn có thể chọn bất kỳ mẫu nào trong số các mẫu này phù hợp với cấu trúc ứng dụng của mình. Để tìm hiểu thêm về các mẫu này, hãy đọc về chúng trong tài liệu chính thức .

Bài viết này tập trung vào việc tạo trang web tĩnh và định tuyến động. Việc sử dụng các mẫu này yêu cầu sử dụng các phương pháp tìm nạp dữ liệu getStaticPropsvà . getStaticPathsCác phương pháp này đóng vai trò duy nhất trong việc thu thập dữ liệu.

Chúng ta đã nói về dữ liệu động trong một thời gian. Hãy hiểu điều đó thực sự có nghĩa là gì.

Giả sử chúng tôi có danh sách người dùng trong một ứng dụng đang được hiển thị trên trang web và chúng tôi muốn nhận thông tin duy nhất cho người dùng khi chúng tôi nhấp vào tên của họ - thông tin chúng tôi nhận được sẽ thay đổi theo hành động chúng tôi thực hiện (nhấp vào tên người dùng).

Chúng tôi muốn một cách hiển thị dữ liệu đó trên một trang (hoặc màn hình) duy nhất trong ứng dụng và getStaticPathsphương pháp tìm nạp dữ liệu cho phép chúng tôi lấy dữ liệu duy nhất cho người dùng. Điều này thường phổ biến trong một mảng các đối tượng người dùng với một khóa ( idhoặc _id) duy nhất, tùy thuộc vào cách đối tượng phản hồi được cấu trúc.

export async function getStaticPaths() {
  return {
    paths: {
      [{
        params: {
          uniqueId: id.toString()
        }
      }],
      fallback: false
    }
  }
}

Khóa duy nhất thu được từ getStaticPathsphương thức (thường được gọi là tham số, viết tắt là params) được truyền dưới dạng đối số thông qua contexttham số trong getStaticProps.

Điều này đưa chúng ta trở lại thực tế là getStaticPathskhông thể làm việc mà không có getStaticProps. Cả hai đều hoạt động cùng nhau, bởi vì bạn sẽ cần chuyển giá trị duy nhất idtừ ​​đường dẫn được tạo tĩnh làm đối số cho contexttham số trong getStaticProps. Đoạn mã dưới đây minh họa điều này:

export async function getStaticProps(context) {
  return {
    props: {
      userData: data,
    },
  }
}

Nhược điểm của việc sử dụng các phương pháp tìm nạp dữ liệu gốc của Next.Js 

Bây giờ chúng ta đã hiểu một chút về tìm nạp dữ liệu động trong Next.js, hãy xem xét nhược điểm của việc sử dụng hai phương pháp tìm nạp dữ liệu nói trên.

Lấy dữ liệu từ một API công khai không yêu cầu ủy quyền với một số loại khóa API trong quá trình tìm nạp dữ liệu có thể được thực hiện với getStaticPropsgetStaticPaths.

Hãy xem cả hai trong số chúng dưới đây:

// getStaticPaths
export async function getStaticPaths() {
  const response = fetch("https://jsonplaceholder.typicode.com/users")
  const userData = await response.json()

 // Getting the unique key of the user from the response
 // with the map method of JavaScript.
  const uniqueId = userData.map((data) => {
    return data.id
  })

  return {
    paths: {
      [{
        params: {
          uniqueId: uniqueId.toString()
        }
      }],
      fallback: false
    }
  }
}

Bạn sẽ nhận thấy rằng giá trị duy nhất idnhận được từ mapphương thức JavaScript và chúng tôi sẽ gán nó dưới dạng giá trị thông qua contexttham số của getStaticProps.

export async function getStaticProps(context) {
  // Obtain the user’s unique ID.
  const userId = context.params.uniqueId

  // Append the ID as a parameter to the API endpoint.
  const response = fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
  const userData = await response.json()
  return {
    props: {
      userData,
    },
  }
}

Trong đoạn mã trên, bạn sẽ thấy rằng một biến có tên userIdđã được khởi tạo và giá trị của nó được nhận từ contexttham số.

Giá trị đó sau đó được thêm vào làm tham số cho URL cơ sở của API.

Lưu ý: Chỉ có thể xuất các phương thức getStaticPropsvà phương thức tìm nạp dữ liệu từ một tệp trong thư mục Next.js.getStaticPathspages

Điều đó làm được khá nhiều điều đó đối với một API công khai. Nhưng khi bạn đang xây dựng một ứng dụng yêu cầu người dùng đăng nhập, đăng xuất và có thể thực hiện một số tìm nạp dữ liệu trong ứng dụng khi họ đăng nhập bằng tài khoản của mình, luồng ứng dụng sẽ khác.

Tìm nạp dữ liệu trong hệ thống đã xác thực. 

Quy trình lấy dữ liệu trong một hệ thống đã xác thực hoàn toàn khác với cách thông thường mà chúng tôi lấy dữ liệu từ API công khai.

Hình dung tình huống này: Một người dùng đăng nhập vào một ứng dụng web và sau đó truy cập hồ sơ của họ. Trên trang hồ sơ của họ (khi nó được hiển thị), họ có thể xem và thay đổi thông tin mà họ đã cung cấp khi đăng ký.

Để điều này xảy ra, phải có một số loại xác minh dữ liệu đang được gửi đến người dùng bởi nhà phát triển đã xây dựng giao diện. May mắn thay, có một mẫu phổ biến để cấp quyền cho người dùng khi họ đăng nhập vào hệ thống: Mã thông báo web JSON (JWT).

Khi người dùng đăng ký sử dụng ứng dụng của bạn lần đầu tiên, thông tin chi tiết của họ được lưu trữ trong cơ sở dữ liệu và JWT duy nhất được chỉ định cho lược đồ của người dùng đó (tùy thuộc vào cách thiết kế API back-end).

Khi người dùng cố gắng đăng nhập vào ứng dụng của bạn và thông tin đăng nhập của họ khớp với những gì họ đã đăng ký ban đầu, điều tiếp theo mà các kỹ sư front-end chúng tôi phải làm là cung cấp trạng thái xác thực cho người dùng để chúng tôi có thể có được các chi tiết cần thiết, một trong số đó là JWT.

Có nhiều trường phái suy nghĩ khác nhau về cách bảo vệ người dùng auth-state, bao gồm sử dụng Redux, Composition trong React và API ngữ cảnh của React (tôi khuyên bạn nên sử dụng API ngữ cảnh). Bài báo của Átila Fassina đề cập đến các mô hình quản lý nhà nước trong Next.js.

Cách tiếp cận phổ biến là lưu trữ JWT localStorage- ít nhất là để bắt đầu, nếu chúng tôi đang xem xét vấn đề bảo mật một cách nghiêm ngặt. Nên lưu trữ JWT của bạn trong một httpOnlycookie để ngăn chặn các cuộc tấn công bảo mật như giả mạo yêu cầu trên nhiều trang web (CSRF) và tập lệnh giữa các trang web (XSS).

Một lần nữa, cách tiếp cận này chỉ có thể thực hiện được nếu phần mềm trung gian cookie thích hợp được cung cấp trong API mà các kỹ sư back-end đã xây dựng.

Nếu bạn không muốn phải tìm hiểu cách các kỹ sư back-end đã thiết kế API, thì một cách thay thế để xác thực trong Next.js là sử dụng dự án xác thực nguồn mở NextAuth.js.

Khi mã thông báo ở localStoragephía máy khách, các lệnh gọi API yêu cầu mã thông báo người dùng làm phương tiện ủy quyền có thể được thực hiện mà không gặp lỗi 501 (trái phép).

headers: {
  "x-auth-token": localStorage.getItem("token")
}

Tìm nạp dữ liệu bằng useRoutermóc 

Trong phần đầu tiên, chúng ta đã biết quá trình tìm nạp dữ liệu động hoạt động như thế nào trong Next.js đối với một ứng dụng không yêu cầu xác thực.

Trong phần này, chúng ta sẽ xem xét cách bỏ qua vấn đề của các phương thức tìm nạp dữ liệu getStaticPropsgetStaticPathsném dấu referenceError(“ localStoragelà không xác định”) khi chúng tôi cố gắng lấy mã thông báo của người dùng localStorage.

Lỗi này xảy ra do hai phương pháp tìm nạp dữ liệu luôn chạy trên máy chủ ở chế độ nền, do đó làm cho localStorageđối tượng không khả dụng với chúng, vì nó ở phía máy khách (trong trình duyệt).

API bộ định tuyến của Next.js tạo ra nhiều khả năng khi chúng tôi xử lý các tuyến và dữ liệu động. Với useRouterhook, chúng ta có thể lấy dữ liệu duy nhất cho người dùng dựa trên ID duy nhất của họ.

Hãy xem đoạn mã dưới đây để bắt đầu:

// pages/index.js

import React from "react";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import Link from "next/link";

const Users = () => {
  const [data, setData] = React.useState([])
  const [loading, setLoading] = React.useState(false)

  const getAllUsers = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: userEndpoints.getUsers,
        headers: {
          "x-auth-token": localStorage.getItem("token"),
          "Content-Type": "application/json",
        },
      });
      const { data } = response.data;
      setData(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  return (
    <React.Fragment>
      <p>Users list</p>
      {data.map((user) => {
          return (
            <Link href={`/${user._id}`} key={user._id}>
              <div className="user">
                <p className="fullname">{user.name}</p>
                <p className="position">{user.role}</p>
              </div>  
            </Link>
          );
        })}
    </React.Fragment>
  );
};

export default Users;

Trong đoạn mã trên, chúng tôi đã sử dụng useEffecthook để lấy dữ liệu khi trang được hiển thị lần đầu tiên. Bạn cũng sẽ nhận thấy rằng JWT được gán cho x-auth-tokenkhóa trong tiêu đề yêu cầu.

Khi chúng tôi nhấp vào một người dùng, Linkthành phần sẽ chuyển chúng tôi đến một trang mới dựa trên ID duy nhất của người dùng. Khi chúng tôi ở trên trang đó, chúng tôi muốn hiển thị thông tin dành riêng cho người dùng đó với id.

Cái useRoutermóc cung cấp cho chúng tôi quyền truy cập vào pathnametrong tab URL của trình duyệt. Với điều đó tại chỗ, chúng tôi có thể nhận được tham số truy vấn của tuyến đường duy nhất đó, là id.

Đoạn mã dưới đây minh họa toàn bộ quá trình:

// [id].js

import React from "react";
import Head from "next/head";
import axios from "axios";
import { userEndpoints } from "../../../routes/endpoints";
import { useRouter } from "next/router";

const UniqueUser = () => {
  const [user, setUser] = React.useState({
    fullName: "",
    email: "",
    role: "",
  });
  const [loading, setLoading] = React.useState(false);
  const { query } = useRouter();

  // Obtaining the user’s unique ID with Next.js'
  // useRouter hook.
  const currentUserId = query.id;

  const getUniqueUser = async () => {
    try {
      setLoading(true);
      const response = await axios({
        method: "GET",
        url: `${userEndpoints.getUsers}/${currentUserId}`,
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": localStorage.getItem("token"),
        },
      });
      const { data } = response.data;
      setUser(data);
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  React.useEffect(() => {
    getUniqueUser();
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>
          {`${user.fullName}'s Profile | "Profile" `}
        </title>
      </Head>
        <div>
          <div className="user-info">
            <div className="user-details">
              <p className="fullname">{user.fullName}</p>
              <p className="role">{user.role}</p>
              <p className="email">{user.email}</p>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};
export default UniqueUser;

Trong đoạn mã trên, bạn sẽ thấy rằng chúng tôi đã hủy đối tượng truy vấn khỏi useRouterhook, đối tượng mà chúng tôi sẽ sử dụng để lấy ID duy nhất của người dùng và chuyển nó làm đối số cho điểm cuối API.

const {query} = useRouter()
const userId = query.id

Khi ID duy nhất được thêm vào điểm cuối API, dữ liệu dành cho người dùng đó sẽ được hiển thị sau khi trang được tải.

Sự kết luận 

Tìm nạp dữ liệu trong Next.js có thể trở nên phức tạp nếu bạn không hiểu đầy đủ về trường hợp sử dụng của ứng dụng của mình.

Tôi hy vọng bài viết này đã giúp bạn hiểu cách sử dụng API bộ định tuyến của Next.js để lấy dữ liệu động trong các ứng dụng của bạn.

Nguồn bài viết gốc tại https://www.smashingmagazine.com

#nextjs #api #database

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Eva  Murphy

Eva Murphy

1625751960

Laravel API and React Next JS frontend development - 28

In this video, I wanted to touch upon the functionality of adding Chapters inside a Course. The idea was to not think much and start the development and pick up things as they come.

There are places where I get stuck and trying to find answers to it up doing what every developer does - Google and get help. I hope this will help you understand the flow and also how developers debug while doing development.

App url: https://video-reviews.vercel.app
Github code links below:
Next JS App: https://github.com/amitavroy/video-reviews
Laravel API: https://github.com/amitavdevzone/video-review-api

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #api #react next js #next #frontend #development