Using JavaScript and TypeScript Together in a Next.js Project

To use both JavaScript (.js) and TypeScript (.ts) in a Next.js project, follow these steps:


1. Set Up a Next.js Project

If you don’t already have a Next.js project, create one by running:

npx create-next-app my-next-app


2. Add TypeScript Support

  1. Navigate to your project directory: cd my-next-app
  2. Install TypeScript and required types: npm install --save-dev typescript @types/react @types/node
  3. Create an empty tsconfig.json file in the root of your project: touch tsconfig.json
  4. Run the development server: npm run dev Next.js will automatically detect the tsconfig.json file and set it up for you with default settings. The file will be populated with a basic configuration.

3. Mix JavaScript and TypeScript Files

  • You can now write files in .js, .jsx, .ts, and .tsx extensions. Next.js supports mixing these file types seamlessly.

4. Update the tsconfig.json for Compatibility

If needed, you can configure tsconfig.json to allow JavaScript files:

{
  "compilerOptions": {
    "allowJs": true,
    "jsx": "preserve",
    "target": "es5",
    "module": "esnext",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"]
    },
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"],
  "exclude": ["node_modules"]
}

The allowJs option enables JavaScript files in a TypeScript project.


5. Using JavaScript and TypeScript Together

  • JavaScript Example (pages/index.js):
export default function Home() {
  return <h1>Hello from JavaScript!</h1>;
}
  • TypeScript Example (pages/about.tsx):
import React from 'react';

const About: React.FC = () => {
  return <h1>Hello from TypeScript!</h1>;
};

export default About;

6. Linting (Optional)

To ensure consistent coding standards, install ESLint and configure it to support both JavaScript and TypeScript:

npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin


7. Handling TypeScript Errors

If you encounter TypeScript errors, you can temporarily bypass them using // @ts-ignore above the problematic line. However, this should be avoided in production code.

// @ts-ignore
const message = "This is allowed temporarily.";


Conclusion

Next.js supports both JavaScript and TypeScript out of the box, and you can mix them as needed. TypeScript enhances the development experience by adding static typing, while JavaScript can be used for quick prototyping or legacy code integration.

Mastering External API Integration in Next.js: A Beginner-Friendly Guide

Next.js, a powerful React framework, makes integrating external APIs straightforward and efficient. In this blog, we’ll explore how to fetch data from an API. We will also cover the best practices for managing data requests. Additionally, you’ll learn where to place your logic for optimal performance.

1. Understanding API Calls in Next.js

Next.js offers both client-side and server-side data fetching techniques. Depending on your use case, you can decide which one fits your needs.

2. Client-Side Fetching

Client-side fetching is ideal for dynamic data that doesn’t need to be indexed by search engines.

Example: Fetching data using useEffect.

import { useEffect, useState } from 'react';  

export default function ClientSideExample() {  
  const [data, setData] = useState(null);  

  useEffect(() => {  
    fetch('https://jsonplaceholder.typicode.com/posts')  
      .then((response) => response.json())  
      .then((data) => setData(data));  
  }, []);  

  return (  
    <div>  
      <h1>Client-Side Fetched Data</h1>  
      {data ? data.map((item) => <p key={item.id}>{item.title}</p>) : 'Loading...'}  
    </div>  
  );  
}

3. Server-Side Rendering (SSR)

For SEO-sensitive pages, SSR ensures data is fetched on the server before rendering the page.

Example: Using getServerSideProps.

export async function getServerSideProps() {  
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');  
  const data = await res.json();  

  return { props: { data } };  
}  

export default function ServerSideExample({ data }) {  
  return (  
    <div>  
      <h1>Server-Side Fetched Data</h1>  
      {data.map((item) => (  
        <p key={item.id}>{item.title}</p>  
      ))}  
    </div>  
  );  
}

4. Static Site Generation (SSG)

For pages where data doesn’t change often, SSG is the best choice.

Example: Using getStaticProps.

export async function getStaticProps() {  
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');  
  const data = await res.json();  

  return { props: { data } };  
}  

export default function StaticExample({ data }) {  
  return (  
    <div>  
      <h1>Static-Site Generated Data</h1>  
      {data.map((item) => (  
        <p key={item.id}>{item.title}</p>  
      ))}  
    </div>  
  );  
}

5. Best Practices for Consuming APIs

  • Use Environment Variables: Store API keys and sensitive information in .env.local.
  • Cache Responses: Use caching for frequently requested data to improve performance.
  • Error Handling: Always handle API errors gracefully using try-catch blocks or response checks.
  • Avoid Redundant Requests: Use Next.js’s data fetching methods effectively to avoid unnecessary client-side calls.

6. Final Thoughts

Next.js simplifies API integration with its robust data-fetching methods. Choosing the right approach—client-side, SSR, or SSG—based on your application’s needs will ensure optimal performance and a better user experience.

Happy coding! 🚀