Get URL pathname in nextjs

If you want to access the router object inside any functional component in your app, you can use the useRouter hook, here’s how to use it: import { useRouter } from ‘next/router’ export default function ActiveLink({ children, href }) { const router = useRouter() const style = { marginRight: 10, color: router.pathname === href ? … Read more

You’re importing a component that needs useState. It only works in a Client Component, but none of its parents are marked with “use client”

In the app directory, by default, Next.js uses Server Components, where the JSX gets compiled to “pure HTML” and sent to the browser. Like any traditional Backend with a templating engine, such as Express with EJS, and Laravel with Blade. This is for better performance, as you can read on the doc: Server Components allow … Read more

TypeError [ERR_INVALID_URL]: Invalid URL using Next-auth only in Production

I think it’s because you’re using the development link NEXTAUTH_URL=”http://localhost:3000″ in production. Instead, use the live link NEXTAUTH_URL=”yourwebsite.com” in production. Also, instead of doing an if-statement to check whether you’re in development or in production, have 2 .env files – one locally with the localhost url, and the one on live with the live url. … Read more

What’s the difference between exposing environment variables in nextjs through the next.config.js vs with the NEXT_PUBLIC prefix?

NEXT_PUBLIC is a new feature added. Before, in order to set up environment variables, we had to set up both server and client, separately. Environment variables that are placed in the .env file would be available only on the server-side, if you want to make your env variables available on the client-side you had to … Read more

For Next.js Dynamic Routes, it is possible to combine a string with a [slug]?

While Next.js doesn’t provide built-in support for partial dynamic routes (like something-[slug]), you can work around it by setting up an actual dynamic route and use rewrites to map the incoming URL (in the format you want) to that route. For instance, you could setup a dynamic route under /pages/something/[slug].jsx, then configure a rewrites rule … Read more

how can I use top level “await” in typescript next.js

It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await. module.exports = { webpack: (config) => { // this will override the experiments config.experiments = { …config.experiments, topLevelAwait: true }; // this will just update topLevelAwait property of … Read more