13 Feb 2024
In a Next.js application, there are several ways to transmit data between pages. The choice of method depends on the type of data you want to pass and the specific use case. Here are some common approaches:
-
Query Parameters: You can use query parameters to pass data through the URL. These parameters are accessible in the target page's
context.query
object. For example:// Sender page import { useRouter } from 'next/router'; const Page = () => { const router = useRouter(); const handleClick = () => { router.push('/receiver?data=example'); }; return ( <button onClick={handleClick}>Go to Receiver</button> ); }; // Receiver page const ReceiverPage = ({ query }) => { return ( <div>Data received: {query.data}</div> ); }; export default ReceiverPage;
-
URL Path: You can also include data in the URL path using dynamic routes. For example:
// Sender page import { useRouter } from 'next/router'; const Page = () => { const router = useRouter(); const handleClick = () => { router.push('/receiver/example'); }; return ( <button onClick={handleClick}>Go to Receiver</button> ); }; // Receiver page const ReceiverPage = ({ query }) => { return ( <div>Data received: {query}</div> ); }; export async function getServerSideProps({ params }) { return { props: { query: params.data, }, }; } export default ReceiverPage;
-
State Management: You can use state management libraries like Redux or React Context to share global state between components, including pages.
-
LocalStorage/SessionStorage: Storing data in
localStorage
orsessionStorage
allows you to persist data between page loads. However, keep in mind that this method is client-side and can be less secure for sensitive data. -
Cookies: Cookies can be used to store small pieces of information that are sent between the client and server. The
js-cookie
library is commonly used for this purpose. -
Server-Side Rendering (SSR) with
getServerSideProps
: You can fetch data on the server usinggetServerSideProps
and pass it as props to the page. This is suitable for scenarios where you need to fetch data on every request.
These are some of the common methods for transmitting data between pages in a Next.js application. The choice of method depends on factors such as the type of data, the desired behavior, and performance considerations.