JavaScript/Next.js

Next.js - userAgent 정보 확인

크런키스틱 2023. 6. 23. 14:21
728x90

프로젝트를 하다보면 웹, 모바일 웹에 따라 서비스가 달라지는 경우가 있다. 예를 들어, 반응형보다는 모바일 웹에서는 컴포넌트 구성 자체가 달라지는 경우를 들 수 있다. 또한, 접속 기기에 따른 서비스 제공의 차이 혹은 정보들이 필요할 때 userAgent를 통해 접속 정보들을 확인할 수 있다.

 

이를 위한 방법으로, request-header 안에 담겨있는 userAgent를 통해 확인하거나, react-device-detect라는 npm을 사용하면 된다.

 

1. SSR (request-header)

import { GetServerSideProps, GetServerSidePropsContext, NextPage } from "next";

const Home: NextPage = (props) => {
	console.log(props.userAgent);
    return (
    	<div></div>
    )
}

export const getServerSideProps: GetServerSideProps = async (
	context: GetServerSidePropsContext<ParsedUrlQuery>
) => {
	const userAgent = context.req.headers['user-agent'];
    return {
    	props: {userAgent}
    }
}

이는 각 페이지에서 ssr을 통해 확인하는 방법으로 전체에 대한 접속여부 한번을 알고 싶다면 _app.tsx에 getInitialProps의 header를 통해 얻으면 된다.

 

2. react-device-detect

 

- 설치

yarn add react-device-detect

 

- 모바일 인식

import {isMobile} from 'react-device-detect';

const test = () => {
	return (
    	<>
        	{isMobile ? <div>모바일 기기용 컴포넌트</div> : <div>컴포넌트</div>}
        </>
    )
}

 

- 브라우저 인식

import {isIE} from 'react-device-detect';

const test = () => {
	return (
    	<>
        	{isIE ? <div>IE는 지원하지 않습니다.</div> : <div>컴포넌트</div>}
        </>
    )
}
import {browserName} from 'react-device-detect';

const test = () => {
	return (
    	<>
        	{browserName === "Chrome" && <div>컴포넌트</div>}
        </>
    )
}

 

그 외에도 이렇게 많은 props들이 있어 본인의 프로젝트에 필요한 props를 골라서 쓰면 된다.

728x90